Swift Optional type _09_optional basic use

Source: Internet
Author: User

//: Playground-noun:a Place where people can playImport UIKit//variables or constants in 1.Swift must be initialized or assigned before they can be usedvarMyint:intmyint=1print (MYINT)//2. Use an optional type to handle a condition where the value of a constant or variable may be missingLet Correctstr ="123"varCorrectint =Int (CORRECTSTR) let Wrongstr="Hello"varWrongint =Int (WRONGSTR)//There are two states of an optional type: The state of an unreasonable value is not possible, and security can be ensured//(1) nil means no value//(2) with legal value//3. Defining variables for optional typesvarMyint2:int?print (MyInt2)varStr1:string?//4. A variable of a non-optional type cannot be assigned a value of nil//var str2:string = nil//5. Optional type of forced unpackingLet str2:string? ="Hello"print (str2) print (str2!)//the prerequisite for unpacking is that it must be an optional type, and that the value cannot be nil//6. Implicit unpacking: To determine if an optional type has a legal value, add it directly after the type name! Implicit unpacking, no more forcing unpacking when using an optional type variable//var result:int! =//print (Result)//7. Optional bindings: Optional types are assigned and judged by an if or while statement, called an optional binding//if the value of the optional type is nil, the IF condition is not true and the contents of the {} are not executed//If the optional type has a legal value, the value of the legal value is assigned to result, and if condition Solutionkeys, the contents of {} are executed. varPossiblenum:int? =NilifLet result =Possiblenum {print (Result)}//define a function to convert the string to int

Swift Optional type _09_optional basic use

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.