Conditionally binding to an existing property

153 Views Asked by At

I'm looking for a way to improve this pattern of code:

struct Struct {
    let i: Int

    init?(i: Int?) {
        guard let unwrappedI = i else { return nil }
        self.i = unwrappedI
    }
}

It'd be nice to remove the unwrappedI temporary variable. Any suggestions?

2

There are 2 best solutions below

0
On

Well I was sure overthinking this... I need to sleep.

struct Struct {
    let i: Int

    init?(i: Int?) {
        if let i = i { self.i = i }
        else { return nil }
    }
}
7
On

I would have said:

struct Struct {
    let i: Int

    init?(i: Int?) {
        if i == nil {return nil}
        self.i = i!
    }
}

I think that captures your initial desire to exit early and avoids the if/else you were trying to avoid, with no intermediate variable. To unwrap i, just unwrap it! No need for if let or guard let or any of that fancy stuff.

(On the other hand, I have to ask: if passing nil to the initializer is considered failure, why offer to accept an Optional in the first place?)