Optionals: Gold Challenge Solutions

I think I’m on the right track. I arrived at the correct string. Any more elegant solutions?

For reference, this is the bucketList array of Strings:

0 [“Climb Mt. Everest”]
1 [“Read War and Peace”]
2 [“Go on an Arctic expedition with friends”]
3 [“Scuba dive in the Great Blue Hole”]
4 [“Find a triple rainbow”]

//Page 103 - Optionals: Gold Challenge
let position = bucketList.firstIndex(of: "Go on an 
Arctic expedition with friends") //2

if var newPosition = position {
    newPosition += 2 //4
    print(bucketList[newPosition]) //Find a triple rainbow
}
1 Like

I’m using the 3rd Edition Swift Programming by Mikey Ward

I’m new to programming so …

This is what I did and it seems to work. I commented out a bunch of lines to keep this simple.

Console:
[“Climb Mt. Everest”, “Read War and Peace”, “Go on an Arctic expedition”, “Scuba dive in the Great Blue Hole”, “Find a triple rainbow”]
Find a triple rainbow

I took a similar approach, but included a check to verify that the new index was also valid. My code is as follows:

import Cocoa

var bucketList = ["Climb Mt. Everest"]    
bucketList.append("Read War and Peace")
bucketList.append("Go on an Arctic expedition")
bucketList.append("Scuba dive in the Great Blue Hole")
bucketList.append("Find a triple rainbow")
if let initialIndex = bucketList.firstIndex(of: "Go on an Arctic expedition"),
   let newIndex = bucketList.index(initialIndex, offsetBy: 2, limitedBy: bucketList.endIndex - 1) {
    print(bucketList[newIndex])
}