Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between ? and ! in Swift Language? [duplicate]

Tags:

swift

I read a lot of articles online and book (Apple) but I am not able to find out the difference between ? and ! operator in Swift language.

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
    {

    }

    override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
        return 1;
    }

In the code above the first func declares the tableView as ! and in the second function tableView is declared as ?.

like image 231
john doe Avatar asked Jun 30 '14 18:06

john doe


1 Answers

As per the official Apple docs:

When working with optional values, you can write ? before operations like methods, properties, and subscripting. If the value before the ? is nil, everything after the ? is ignored and the value of the whole expression is nil. Otherwise, the optional value is unwrapped, and everything after the ? acts on the unwrapped value. In both cases, the value of the whole expression is an optional value.

Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.” This is known as forced unwrapping of the optional’s value (...)

Apple Inc. 'The Swift Programming Language'. iBooks. https://itun.es/nl/jEUH0.l

like image 117
Joride Avatar answered Jan 15 '23 16:01

Joride