0

I have a class ScoreModel simplified to:

class ScoreModel {
    var teamName : String!
}

Which could be placed in an Init() function since it needs to always be set, but that does not help my understanding of the problem:

I have a ScoreViewController : UIViewController where I use the non-optional ScoreModel:

class ScoreViewController {
    var scoreModel : ScoreModel!
}

which is passed using prepareForSegue. This is all working but when i want to get the teamName it is returned as optional:

override func viewWillAppear(_ animated : Bool) {
    let name = scoreModel.teamName
    print(name) 
}

this outputs:

Optional("teamNameEntered")

But the variable is marked with an exclamation mark in the ScoreModel so it should be unwrapped. Why is it still returning an Optional?

EDIT: as requested the prepareForSegue method:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destinationVC = segue.destination as? ScoreViewController {
        let scoreModel = self.scoreModel ?? ScoreModel()
        destinationVC.scoreModel = scoreModel
    }
}
Emptyless
  • 2,964
  • 3
  • 20
  • 30

1 Answers1

0

First of all, your scoreModel is not non-optional.

You can declare optional variables using exclamation mark instead of a question mark. Such optional variables will unwrap automatically and you do not need to use any further exclamation mark at the end of the variable to get the assigned value.

In your case, you can assign teamName an optional value or a non optional value. So if it is assigned with an optional value, you need to unwrap it to use.

Anusha Kottiyal
  • 3,855
  • 3
  • 28
  • 45
  • Even though it is marked with an '!' I still have to unwrap it? That is strange practice since I would crash my own app if I apply an optional to something I defined to only be non-optional. – Emptyless Jan 06 '17 at 22:46
  • 'teamName` is still optional in your case. You just marked it with `!` for automatic unwrap. – Anusha Kottiyal Jan 06 '17 at 22:50
  • 1
    Yes and the automatic unwrapping part is failing ;) That is the point of my question – Emptyless Jan 06 '17 at 22:51