2

I have a structure in one ViewController which has a couple of non-optional members like:

struct MyStruct {
    let id: Int64!
    let name: String!
    func checkValues() -> Bool {
        if id == nil || name == nil {
            return false
        } else {
            print("id: \(id) name: \(name)"); return true
        }
    }
}

I create an instance of the struct in another VC (let temp = ViewController.MyStruct(id: 10, name: "Example")) and pass it to the one where I created the struct via a Segue. When executing temp.checkValues() I get

id: Optional(10) name: Optional("Example")

From my understanding of (non-)optionals I shouldn't get the Optional() since I declared the variables with !. Did I get it wrong? Right now I just put an exclamation mark whenever I use it. I also tried using init in the struct but that didn't change anything. Since this is not as intended (if I'm right) I fear I didn't get the full concept... Please tell me what is wrong with my code / me.

Hamish
  • 78,605
  • 19
  • 187
  • 280
Michael
  • 657
  • 5
  • 22

2 Answers2

7

Did I get it wrong?

Yes. Your variables are optionals - the ! operator is a force unwrap operator, so your variables are implicitly unwrapped. If you don't want your variables to be optionals, just drop !.

The ! operator exists in Swift to facilitate bridging from Objective-C, for instance for IBOutlet variables. Using ! operator aside from that is a bad practice.

mag_zbc
  • 6,801
  • 14
  • 40
  • 62
  • Thanks a lot! That makes sense... I had the wrong impression that when adding the `!` I would make sure that they cannot be optionals... – Michael Sep 06 '17 at 13:25
5

! is an implictly unwrapped optional. Everything variable declaration's type that ends with ! is an optional. You dont have to declare them to be Optionals. Just use them normally and the initializer will take care of them:

struct MyStruct {
    let id: Int64
    let name: String
    func checkValues() -> Bool {
        print("id: \(id) name: \(name)"); return true
    }
}
Papershine
  • 4,995
  • 2
  • 24
  • 48