othomas
othomas

Reputation: 256

Why do implicitly unwrapped optionals copy as optional?

In the below code, why is test.implicitString an optional, even though the property is stored as implicitly unwrapped? I believe I need the properties to be implicitly unwrapped because my initializers call functions to initialize all values (so I can use the same function later in an update method). Is there an easy way to make it so these properties are non-optional while still allowing me to initialize the properties via a method call from within init()?

class Test {
  var implicitString: String!
  init(string: String) {
    implicitString = string
  }
}

let test = Test(string: "Hello world")

let shouldBeString = test.implicitString

// 1: Prints Optional<String> instead of String
print(type(of: shouldBeString))

// 2: Prints Optional("Hello world") instead of "Hello World"
print(String(describing: test.implicitString))

Upvotes: 0

Views: 223

Answers (2)

Joakim Danielson
Joakim Danielson

Reputation: 51831

Since you have an init method that initialise the property you can simply remove the implicit unwrapping.

class Test {
  var implicitString: String
  init(string: String) {
    implicitString = string
  }
}

Upvotes: 2

alanpaivaa
alanpaivaa

Reputation: 2089

You can get rid of the optional by setting a default value:

class Test {

    var implicitString: String = ""

    init(string: String) {
        update(value: string)
    }

    func update(value: String) {
        implicitString = value
    }

}

Upvotes: 0

Related Questions