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 trialLinus Karlsson
7,402 Pointserror: nil is incompatible with return type 'Friend' ???
Why is my Xcode saying this: "error: nil is incompatible with return type 'Friend' "
struct Person {
let firstName: String
let middleName: String?
let lastName: String
func fullName() -> String {
if middleName == nil {
return firstName + " " + lastName
} else {
return firstName + " " + middleName! + " " + lastName
}
}
}
let me = Person(firstName: "Linus", middleName: nil, lastName: "Karlsson")
me.fullName()
let airportCodes = ["CDG": "Charles De Gaulle"]
let newYorkAirport = airportCodes["JFK"]
// Optional Binding Using If Let
if let newYorkAirport = airportCodes["JFK"] {
print(newYorkAirport)
} else {
print("Whoops! That key does not exist!")
}
let weatherDictionary: [String : [String : String]] = [
"currently" : ["temperature": "22.3"],
"daily" : ["temperature": "22.3"],
"weekly" : ["temperature": "22.3"]
]
if let dailyWeather = weatherDictionary["daily"] {
if let highTemp = dailyWeather["temperature"] {
print(highTemp)
}
}
if let dailyWeather = weatherDictionary["daily"], let highTemperature = dailyWeather["temperature"] {
print(highTemperature)
}
// Downsides to using If Let
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
}
}
1 Answer
Linus Karlsson
7,402 PointsFound the answer myself!
I forgot the question mark after "Friend" in
func new(friendDictionary: [String : String]) -> Friend {
This is how it should be
func new(friendDictionary: [String : String]) -> Friend? {