I'm trying to understand how init!()
works in Swift. Here's my test:
struct InitTest {
var text: String
init!(text: String) {
self.text = text
}
}
let testResult = InitTest(text: "Hello!")
For my understanding, testResult should be of type InitTest
(unwrapped), but it's actually still InitTest?
.
How is init!()
different from init?()
then?
InitTest(text: "Hello!")
returns an implicitly unwrapped optional, which is an optional that is unwrapped if necessary. For example you can access its properties without explicit unwrapping
let string = InitTest(text: "Hello!").text
or pass it to functions taking a (non-optional) InitTest
argument:
func foo(_ x: InitTest) { }
foo(InitTest(text: "Hello"))
But the assignment
let testResult = InitTest(text: "Hello!")
makes testResult
a regular ("strong") optional, see SE-0054 Abolish ImplicitlyUnwrappedOptional type and Implicitly unwrapped optional assign in Xcode 8:
If the expression can be explicitly type checked with a strong optional type, it will be.
Actually I cannot think of a good reason to define an init!()
method.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments