Swift Language-optional type

Source: Internet
Author: User

Optional type What is an optional type

There are two possible types of data for an optional value type: A value, no value (nil). Note that you need to add a question mark (?) after the variable type. If int plus question mark (?), the variable is of type int. Question mark (?) is a flag of an optional type.
Optional values can be used if the value is determined

#import Foundationvarnilifnil{     println("not nil")}else{     println("nil")}
How do I get the values in an optional value?

Forced parsing
Note Add an exclamation mark (!) after an optional variable.
An exclamation mark is a flag that forces parsing.

#import Foundation//非nil情况var optValue:Int? = 3println(intValue)  //会打印Optional(3)println//会打印3var intValue:Int = optValue!println(intValue)//可选类型的Int才能赋值为nil,普通的Int只能赋值整型varnil//var intValue2:Int = optValue1!//println(intValue2)

Note If you force resolve no values, you may run the error together. So it's best to add a judgment for nil.

#import Foundationvarnilifnil {     println(optValue1!) }

Optional bindings
Add a temporary amount and assign an optional value to the temporary variable, judging by the if condition to get the value of the optional type
If the variable of an optional type has no value if the condition does not satisfy, if the optional type variable has a value, the value is obtained through the temporary variable

#import Foundationvarnilif let tempValue = optValue1 {     println(tempValue) }

Swift Language-optional type

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.