Group Group Group Group Group Group Group Group Group

raywenderlich.com Forums

Video Tutorial: Beginning Swift 2 Part 7: Arrays & Sets

Learn about arrays and sets in Swift 2.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3250-beginning-swift-2/lessons/8

Hi

can you point me out what i am doing wrong in this

var numbers = [1,2,3,4]

func list(num : [Int]) -> [Int]
{
return num
}
result = list(numbers) --> returns correctly the array of integers

But i wanted to use placeholder during return of array

func list(num : [Int]) -> [res : [Int]]
{
var res: [Int] = []
for x in list
{
res.append(x)
}
return res
}
when i use like above, i am getting error undeclared type res,

can you point me where i am doing wrong

When attempting to do the “long form” of

for restaurantName in restaurantsVisited {
   print("\(restaurantName)")
}

Which I think looks something like this:

for index in 0..<restaurantsVisited {
    let restaurantName = restaurantsVisited<index>
     print("\(restaurantName)")
}

I was told by Playground that I can’t apply 0..< to a set. So what is the long form?

Hey Janice, the for loop index needs to be a number, so you’d need 0..<restaurantsVisited.count.

But that still won’t work! :wink: Because sets are unordered, there’s no concept of accessing set elements by index. If you were really set on the “long form”, you could convert the set to an array and then iterate through:

let restaurantsVisitedArray = Array(restaurantsVisited)
for index in 0..<restaurantsVisitedArray.count {
    let restaurantName = restaurantsVisitedArray[index]
    print("\(restaurantName)")
}

For sets though, since they’re unordered collections the usual thing is just to iterate directly or test whether some element is already in the set.

I hope this helps and thanks for your question!

(Blushing!) I did forget the .count. Thanks!

So is:

 for restaurantName in restaurantsVisited {
   print("\(restaurantName)")
}

the short form of:

let restaurantsVisitedArray = Array(restaurantsVisited)
for index in 0..<restaurantsVisitedArray.count {
    let restaurantName = restaurantsVisitedArray[index]
    print("\(restaurantName)")
}

?