Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

cameron swenson
cameron swenson
9,951 Points

.contains() on an array of a struct

Running the .contians() method on an array of basic types such as Int, String, etc. is fairly straight forward:

let array = [1, 2, 3, 4]
if array.contains(4) {
print("true") 
}

but what about an array of a custom type such as a struct?

struct Dude {
var dudeName: String
var dudeAge: Int
}

let steve = Dude(dudeName: "Steve", dudeAge: 24)
let arrayOfDudes  = [steve , Dude(dudeName: "Josh", dudeAge: 42)]

arrayOfDudes.contains(steve) gives an error.

I found a post on a forum showing me how to do .filter() but I'm not sure that is the cleanest/best method:

struct Dude {
var dudeName: String
var dudeAge: Int
}

let steve = Dude(dudeName: "Steve", dudeAge: 24)
let arrayOfDudes  = [steve , Dude(dudeName: "Josh", dudeAge: 42)]

let found = arrayOfDudes.filter{ $0.name == "Steve"}.count > 0

Following the same logic I found that .contains() would be ran the same way and "throw" the same true flag I'm looking for:

struct Dude {
var dudeName: String
var dudeAge: Int
}

let steve = Dude(dudeName: "Steve", dudeAge: 24)
let arrayOfDudes  = [steve , Dude(dudeName: "Josh", dudeAge: 42)]

let found = arrayOfDudes.contains{ $0.name == "Steve"}

What are the advantages of one or the other? What does the "$0" signify? Is there a smarter way of handling this?

1 Answer

Michael Reining
Michael Reining
10,101 Points

The $0 is shorthand code that can be used for closures. It can be confusing at times.

There is an example here:

http://fuckingswiftblocksyntax.com/

Filter is using functional programming. There are some good references here to learn more about imperative vs. functional programming. They both have their pros and cons.

http://jamesonquave.com/blog/functional-programming-in-swift/

http://www.raywenderlich.com/82599/swift-functional-programming-tutorial

I hope that helps,

Mike

PS: Thanks to the awesome resources on Team Treehouse, I launched my first app.

Now you can practice writing Swift code directly on your iPhone :-)

Code! Learn how to program with Swift