Nurgling96
Nurgling96

Reputation: 576

SubClass of UITableViewController and variable Initialization. iOS, SWIFT

I have a custom class, that subclass UITableViewController or UIViewController. And there I get a error, that every value should be inialized at super.init call. For me, the solution is to set a value for every property/variable, but why i just can't leave it just initializated, without any value? And what should I better do in that situation?

import UIKit
import Foundation


class MSOrder: UITableViewController {
    var orderId: Int
    var orderNumber: Int
    var statusText: String


    init(orderId: Int,
         orderNumber: Int,
         statusText: String) {

            self.orderId = orderId
            self.orderNumber = orderNumber
            self.statusText = statusText

            super.init(style: UITableViewStyle.Plain)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

Upvotes: 0

Views: 146

Answers (1)

the_critic
the_critic

Reputation: 12820

If you declare your properties like this:

class YourViewController{
    var orderId: Int
    var orderNumber: Int
    var statusText: String
}

the controller expects them to contain a value after initialization, whereas if you do this:

class YourViewController{
    var orderId: Int!
    var orderNumber: Int!
    var statusText: String!
}

you tell the compiler that you'll ensure that those values will contain a value when you use them, bypassing the compile-time check. If you know what you are doing (and this is not that uncommon by the way) you can declare the variable types with a ! suffix.

Another option would be to make those properties optional:

class YourViewController{
    var orderId: Int?
    var orderNumber: Int?
    var statusText: String?
}

That way, all the properties are allowed to be nil.

So when accessing those values you have to explicitly unwrap them:

self.statusText! // to get the unwrapped value of type String!

or

self.statusText?.somethingElse() // executes only if the statusText is set, otherwise continues execution of next lines

Values that have a ! as part of their declaration can also be nil, but by specifying the ! you ensure that it has a value when you access it without the need of explicit unwrapping.

let someValue : String!

So this would fail if the value is nil:

self.someValue // if someValue is nil, this will crash!

if you were to do this:

let someValue : String?

it would just carry on, because by specifying the optional ? symbol, you say "Hey, I don't know for sure, but this value could be nil!"

Thus the need to unwrap it:

let iKnowThereIsAValueInSomeValue = self.someValue!

Let me know if something remains unclear.

Upvotes: 1

Related Questions