Bronze, Silver & Gold Challenges


#1

Here are my solutions:

//Bronze
var toDoList = ["Take out the garbage", "Pay bills", "Cross off finished items"]
toDoList.isEmpty // false
//or
toDoList.count // 3

//Silver
var reversedArray = [String]()
for item in toDoList {
    reversedArray.insert(item, at: 0)
}
print(reversedArray) // ["Cross off finished items", "Pay bills", "Take out the garbage"]

// Silver (better)
toDoList.reverse()
print(toDoList) // ["Cross off finished items", "Pay bills", "Take out the garbage"]

// Gold
let index = bucketList.index(of: "Fly hot air balloon to Fiji")
let newIndex = index! + 2  // Unrwap and add 2
let newString = bucketList[newIndex] // Get string at this location and assign to newString
print(newString) // Go on a walkabout in Australia

#2

Yours is a lot better set out than mine haha. I’m struggling to use the APIs to find reverse() though. I found reversed() but that doesn’t exactly output what I need :sweat_smile: How did you navigate to find it? Or am just being stupid. Sorry, really new to coding. I understood Gold though, even the finding of .index(of: element). Thanks, Rhys.


#3

These days you have a lot of options, between Apple’s documentation, stackoverflow and google, you have the foundation to find the hints / tools to solve almost any problem. Not everything can get solved in 5 minutes and some things can! As you continue to do this more, you’ll get into a better rhythm of understanding Apple’s documentation and finding the pieces you need to solve your problems.


#4

Basically came up with the same code as yours aside from the silver challenge, here is my solution:

var toDoList = ["Takeout garbage",
                "Pay bills",
                "Cross off finished items"]

for item in toDoList {
  toDoList.insert(item, at: 0)
  toDoList.remove(at: 3)
}

print(toDoList)

This way you are not creating a new array but instead altering the original. This implementation is limited though as a list with more than 3 items would not work.


#5

If you use
"toDoList.remove(at: toDoList.endIndex - 1)"
it gets rid of the magic number and will let you use for any amount of instances.


#6

I’m a little confused as to how the documentation is organized:
The last part of the Silver Challenge asks to find a more convenient way to reverse
the array, but in the description of Array one only finds the reversed-method, not the
reverse-method.
Explicitly searching for “reverse”, one finds an entry under “MutableCollection”.
I wonder why the reverse-method is not mentioned in the description of Array.


#7

Tiberius,

What if index is nil because the string was not found in the array?

How about…
// Gold
let index = bucketList.index(of: “Fly hot air balloon to Fiji”)
if let newIndex = index + 2 { // Safely Unwrap and add 2
let newString = bucketList[newIndex] // Get string at this location and assign to newString
print(newString) // Go on a walkabout in Australia
}

No errors on nil this way.


#8

It’s a balance of when you already know there’s a value vs not. IF you didn’t know what the array looked like in advance, and wanted to be safer with your code, you’d want it to look more like this:

// New Gold
if let index = bucketList.index(of: "Fly hot air balloon to Fiji") {
    let newIndex = index + 2  //  add 2 and no longer need to unwrap
    if newIndex < bucketList.count  { // Make sure you're still in range
        let newString = bucketList[newIndex] // Get string at this location and assign to newString
        print(newString) // Go on a walkabout in Australia
    } else {
        print("Your newIndex is out of range of the array")
    }
}

#9

Here is my solutions
//Bronze Solution
var toDoList = ["Take out the garbage ", “Pay Bills”, “Cross finished items”]

if toDoList.isEmpty {

print("Yes it is empty \(toDoList.count)")

} else {

print("It is not empty, \(toDoList)")

}

//Silver Solution
let reversedLists = Array(toDoList.reversed())
print(reversedLists) //“Cross finished items”, “Pay Bills”, "Take out the garbage "

//Gold Solution
if let i = bucketList.index(of: “Fly hot air balloon to Fiji”){
let offset = bucketList.index(i, offsetBy: 2) //3
print("(bucketList[offset])") //“Go on a walkabout in Australia”

}


#10

This was my solution, similar to yours but doesn’t matter how long array is
var toDoList = [put in as many strings as you like]
Let Count = toDoList.count. // gives how many instances
for i in 1…Count {
toDoList.append(toDoList[Count-i] //appends
toDoList.remove(at: (Count-i)// deletes the value
}
print(toDoList)

It works from the end of the array, appending each value to the end before deleting the original value.


#11

@kees
I had to do some digging but I found these other type properties. I couldn’t say which one Tiberius is using, but I was also wondering why reversed is in the Array documentation and not reverse. At least this gives me a sense of closure.

https://developer.apple.com/documentation/foundation/nsattributedstring.enumerationoptions/1414984-reverse

https://developer.apple.com/documentation/foundation/nsenumerationoptions/1395159-reverse

https://developer.apple.com/documentation/foundation/nsstring.enumerationoptions/1412250-reverse


#12

Here’s my gold solution. This safely unwraps the Optional Index, checking for nil first:

let optIndex = bucketList.index(of: “Fly hot air baloon to Fiji”)
if optIndex != nil {
let index = optIndex!
let newIndex = bucketList.index(index, offsetBy: 2)
print("(bucketList[newIndex])")
}
//Go on a walkabout in australia


#13

debcat, with optionals you’ll want to do your unwrapping with “if let” structures. Also checking if something != nil isn’t very swifty. So it would look something like (also note your spelling as your code would never run ;):

if let optIndex = bucketList.index(of: "Fly hot air balloon to Fiji") {
    let newIndex = bucketList.index(optIndex, offsetBy: 2)
    print("\(bucketList[newIndex])")
}

#14

Ok, thanks. Hard to shake my old C habits! Don’t know what you mean about spelling, this does run. What did I misspell?


#15

Balloon. also for the print, make sure you include the \ (or perhaps the forum just removed it), otherwise your string interpolation won’t work.


#16

Can someone help me? For the silver challenge I don’t get why if you do

var reversedArray = String
for item in toDoList {
reversedArray.insert(item, at: 0)
}
print(reversedArray) // [“Cross off finished items”, “Pay bills”, “Take out the garbage”]

It reverses the order? Doesn’t the loop go through the array and put “Take out garbage” as index 0?


#17

Each item in the toDoList is inserted at index 0 in reversedArray. As a result, the item that was at index 0 and all items that follow it before the insertion move into higher index positions.

reversedArray = []
insert item1, reversedArray = [item1]
insert item2, reversedArray = [item2, item1]
insert item3, reversedArray = [item3, item2, item1]
insert itemN, reversedArray = [itemN, ..., item3, item2, item1]


#18

hey thank you for sharing results! But i did not get this part of code.How this happens? How the insert method works here?

toDoList = ["Takeout garbage",
                "Pay bills",
                "Cross off finished items"]

for item in toDoList {
    toDoList.insert(item, at: 0)
    toDoList.remove(at: 3)
}

#19

I was really baffled by that as well, but it appears that the list of values for item is preset at the beginning of the loop, and is not affected by the changes made to toDoList within the loop. I added a print statement to print out the list contents each pass through the loop and got the following:

[“Take out the garbage”, “Take out the garbage”, “Pay bills”]
[“Pay bills”, “Take out the garbage”, “Take out the garbage”]
[“Cross off finished items”, “Pay bills”, “Take out the garbage”]

So even though “Cross off finished items” is no longer in the list after the first pass through, it winds up getting put back on the last pass.

However, I’d be reluctant to rely on this behavior. My version looks like this:

if toDoList.count > 1
{
    for index in 0...toDoList.count-2
    {
        var item = toDoList.removeLast()
        toDoList.insert(item, at: index)
    }
}

which maintains the list integrity each pass.


#20

// Silver Challenge - without creating a new variable or altering the array’s order

for item in toDoList.reversed() {
   print(item)
}

This preserves the original array, and space isn’t wasted by creating a new variable. This works if you simply want to see the reverse order of the array printed to the screen.