[swift-evolution] Enforce non-nil assignment to an implicitly unwrapped optional property?

Glen Huang heyhgl at gmail.com
Sun Jul 16 02:30:07 CDT 2017


I want to define a property for a struct/class that is nil after initialization, but later is guaranteed to have a value after I manually assign to it. I think implicitly unwrapped optional property is designed specifically for that.

However, the problem arises when it comes to how do I enforce that I never mistakenly assign nil to this property?

struct Foo {
    var name: String!
}
var foo = Foo()

I can do foo.name = nil and it will compile just fine.

I guess I could do a run-time check with something like:

struct Foo {
    var name: String! {
        willSet {
            if newValue == nil {
                fatalError("nil isn't allowed")
            }
        }
    }
}

But it feels ugly, and seems to be something checkable at compile time.

I could define a new setter method:

struct Foo {
    private(set) var name: String!
    mutating func setName(_ name: String) {
        self.name = name
    }
}

But it feel tedious. Enforcing non-nil assignment probably fits 90% of the use cases of IUOs, since that’s basically their definition. Having to deviate from direct assignment syntax in usage and also define a new setter method for the majority cases seems unfortunate.

I wonder if it’s desirable to define an attribute or something to ask the compiler to only allow non-optionals to be assigned to IUO properties?


More information about the swift-evolution mailing list