//: 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