Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

how will these parameters return a Friend?

The vide gives the following code

struct Friend { let name : String let age : String let address : String?

}

func new(friendDictionary: [String : String]) -> Friend? { if let name = friendDictionary["name"], let age = friendDictionary["age"] { let address = friendDictionary["address"] return Friend(name: name, age: age, address: address) } else { return nil } }

Can someone please explain to me how a dictionary of string to string will return a friend>

1 Answer

Ryan Sady
Ryan Sady
20,594 Points

It lies in the actual return statement within the if-let block. You parse the dictionary values within the if-let statements, grabbing the persons name and age properties. If those succeed and the values exists (the entire purpose of if-let statements), you return a newly constructed Friend object by passing in those two values.

if let name = friendDictionary["name"]" , //you're grabbing the name property here

let age = friendDictionary["age"] { //you're grabbing the age property here

let address = friendDictionary["address"] //you're grabbing the address property here and because it's an optional property in the Friend struct and dictionary values always return as optionals it's ok if it's nil

return Friend(name: name, age: age, address: address) //This is where you're plugging in your name, address, and age values to return a Friend struct.

} else {
return nil //if the name and age properties within your 'friendDictionary' are nil, you return nothing

}
}