0

I have this simple class:

import UIKit

let builtIn = MyClass(n1: 1)
print("DeviceA: \(builtIn.n1)") // DeviceA Optional(1)

class MyClass: NSObject {
    var n1: Int!

    init(n1: Int) {
        super.init()

        self.n1 = n1
    }
}

Why is it DeviceA Optional(1) on the console while n1 is not optional?

I could fix this by print("DeviceA: \(builtIn.n1!)"). But I just don't understand why Optional is there.

Thanks,

quanguyen
  • 1,443
  • 3
  • 17
  • 29
  • @ShamasS: in `print("DeviceA: \(builtIn.n1)")`, I don't mean to convert `String` to `Int`, instead, I want to convert from `Int` to `String`. – quanguyen Jul 20 '17 at 02:52

2 Answers2

1

You have declared n1 as an implicitly unwrapped optional:

var n1: Int!

This means n1 is still an optional, but you are promising the code that it will be non-nil. In order to avoid the optional state you would need to declare at as:

var n1: Int

In that case you either need to make sure to initialize it in your init() function or provide a default init like this:

var n1: Int = 0
davidethell
  • 11,708
  • 6
  • 43
  • 63
0

n1 is an implicitly unwrapped optional.

When printed, it shows that it is, in fact, an optional, even though it behaves like a non-optional variable when used elsewhere.

Check the Swift syntax of optionals here.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223