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

Lana Wong
Lana Wong
3,968 Points

How can I write my code with a failable initializer?

HI. Pasan said to practice once we finished the enumerations and optionals course.
I wrote this code:

struct superHero{
    let name: String
    let power: String
    let city: String?

    func new() -> superHero?{
        if name != nil, power != nil, city != nil{
            return superHero(name: name, power: power, city: city)
        }else{
            return nil
        }
    }
}

//Instances
let someHero = superHero(name: "Spider Man", power: "Shoots spider webs", city: "New York")
let anotherHero = superHero(name: "Wonder Woman", power: "Amazon fighting skills", city: nil)

First of all, how can I write this code with a failable initializer? Second, is this object considered "safe"?

1 Answer

Jeff McDivitt
Jeff McDivitt
23,970 Points

In your code since name and power are not optional they must have a value, you will probably get a warning in Xcode saying that the value will always be true.

Here is how you write it with a failable initializer

struct superHero{

    let name: String
    let power: String
    let city: String?

    init?(name: String, power: String, city: String) {
        if city.isEmpty { return nil }
        self.name = name
        self.power = power
        self.city = city
    }
}

let someHero = superHero(name: "Spider Man", power: "Shoots spider webs", city: "New York")
let anotherHero = superHero(name: "Wonder Woman", power: "Amazon fighting skills", city: "")
Lana Wong
Lana Wong
3,968 Points

What is the city.isEmpty?