[swift-evolution] Initializers

Joe Groff jgroff at apple.com
Fri Feb 3 12:40:04 CST 2017


> On Jan 31, 2017, at 3:52 AM, Victor Petrescu via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 4. Joe Groff says there is already a backdoor of sorts ("There already is a backdoor of sorts. This is one of the intended use cases for implicitly-unwrapped optionals. If you don't want to be hassled by DI, declare a property as T! type, and it will be implicitly initialized to nil, and trap if you try to use it as an unwrapped T without initializing it first."): I'm assuming by T you mean generics. If that is true that may already solve the problem but... generics are a new concept for me (first time I really encountered and used them is now, in swift) but to my understanding their role is to deal with cases you don't know the type. Can you please show how to use this to work around the posted issue?
> 
> Sidenote: There may be another workaround using optionals (Joe Groff answer made it pop in my mind) but... I know the type and value for the variable, it is not optional or nil. Unwrapping each time someone needs it does not look like the best solution to me.

You don't need to understand generics to use implicitly-unwrapped optionals. By `T!` I was referring to the syntax used to represent them; you would write Int! or String! or whatever in your code. For your example, this would let you avoid having to invoke super.init() before resetting `x`:

class A {
     var x:Int! // Int! is nil by default
}

class B : A {
    override init() {
         x = 2 // So we can set it here w/o super.init first
    }
}

print(B().x + 1) // and we don't need to explicitly unwrap it to use it, unlike `Int?`

You're giving up the static guarantee that `x` has a value, so you'll get a runtime error if you try to use it before it's initialized, but that's the same situation you have in Java, where dereferencing an uninitialized object reference gives an NPE. Whether you want the hard guarantee that `x` is never optional from the compiler, or the convenience of leaving that up to runtime checks, is a call you have to make; Swift defaults to the strong guarantee, but implicitly-unwrapped optional types like Int! are intended to give you an out if the static model is too strict or inefficient.

-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170203/f6ab890f/attachment.html>


More information about the swift-evolution mailing list