SWIFT Optional Value

Source: Internet
Author: User

A type definition in Swift is called an optional value, plus one after the variable type. You can define a variable of type optional value and use a forced unpacking when using a variable!.

If there is an optional box on the page to enter the age, you may want to define a variable of an optional value at the time the data is accepted.

var age:int? = 10

var str:string = "Age is" +string (age!)

The following is the data that is taken from an array, and then the existence of a value

var numberoflegs = ["Ant": 6, "snake": 0, "dog": 4]

var possiblelegcount:int? = numberoflegs["Fish"]//Cannot find the corresponding key value will return nil

Determine if Possiblelegcount is nil

if Possiblelegcount = = nil{

println ("Not Found")

}else{

var legcount = possiblelegcount! Forced unpacking

println ("Fish ' s legs is \ (legcount)")

println ("Fish ' s legs is \ (possiblelegcount)")//Use this placeholder method to automatically unpack

}

At this time the Possiblelegcount must be optional value type, otherwise it will be an error. The program will verify that the optional values can be unpacked properly, and the value will be assigned to the Legcount variable if normal.

If let Legcount = possiblelegcount {

println ("Fish ' s legs is \ (legcount)")

}

SWIFT Optional Value

Related Article

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.