Import UIKit
/*:
Optional type ( can have a value , or it can have no value )
* in OC We can assign a value of nil or an object to an object type variable , whereas in Swift if you want to assign a variable to nil It must be explicitly specified as an optional type , which means that the normal variable is not assignable to nil .
Format : data type ?
* after you see the init followed by the next one? The value returned on behalf of the initialization method is optional
Note :
* Optional Types cannot be used directly , and if you are using a value of an optional type , you must unpack the optional type!
* the meaning of unpacking : tell the system optional type of variable , there must be a value , if the value of the optional type does not have a value , we are forced to unpack , then will be an error
Suggestions
* Beginners Learn Swift The Most most painful problem is ?! This syntax , the beginning can be done with the help of the XOCDE compiler reminder ?!, After writing more, you will know when to write?
*/
Let str = "http://www.520it.com/"
Let url = nsurl(string: str)
Print(URL!)
Let num1: Int? = Ten
Let num2: Int =
Note : Swift does not recommend us to use forced unpacking
Let sum = num1! + num2
If let temp = num1
{
let sum = temp + num2
}
/*:
Optional bindings
* specifically used to solve the problem of forced unpacking
* Note : in Development If you want to use a value of an optional type, you may not necessarily use an optional binding , because if the values of the optional type are large and all belong to the same logic , Then accidentally will form if nested
*/
Let url2 = nsurl(string: str)
Print(url2)
The value of the URL2 is taken out to temp, and if the value is taken then it can be entered into the curly brace after the IF, and if no value (nil) is taken, it will not enter curly braces after the if
If let abc = url2
{
print(ABC)
}
Let v1: Int? = Ten
Let v2: Int? =
Let v3: Int? =
If let n1 = v1
{
if let n2 = v2
{
if let n3 = v3
{
let sum = n1 + n2 + N3
}
}
}
/*:
Guard
* function : Similar to optional binding
* only if the condition is False (flase), the code in the curly braces after else will be executed
Format
Guard Conditional expression- else
{
if the condition is false, it will execute .
}
*/
Func Test ()
{
Guard let m1 = v1 Else
{
Print (" no value ")
return
}
Guard let m2 = v2 else
{
Print (" no value ")
return
}
Guard let m3 = V3 Else
{
Print (" no value ")
return
}
let sum = m1 + m2 + m3
}
Test()
Swift 2.0 Syntax Optional type