First, the tuple is unique in swift, there is no tuple-related type in OC, specifically how to use, see the following example bar
//1. Use tuples to define a set of dataLet Infotuple = ("CJH", -,1.8) Let Nametuple= Infotuple.0print (nametuple) let Count=NameTuple.characters.count//2.1 How ordinary tuples are definedLet errormsg = ("Error",123) errormsg.0//2.2 Aliases all elements in a tupleLet ErrorTuple1 = (Error:"Error", ErrorCode:123) errortuple1.errorerrortuple1.0//element aliases for 2.3 tuples are the names of tuplesLet (error,errorcode1) = ("Error",123) ErrorerrorCode1
3. Use one of the tuples to quickly exchange 2 values
var a = 10
var B = 20
(A, b) = (b, a)
A
B
//Exchange completed
Two, optional type. In OC, it is often used to define a variable, but not immediately use, go back to give it a value of 0 or nil, but Swift is a strong type of language, nil is a special type, if it is assigned to nil at the beginning, then when its true type does not match, You will get an error. Therefore, the optional type is available in Swift. Its value is null and has a value of 2. Basic usage is as follows
//1. Define an optional typevarName:string? =Nil//var name:optional<string> = nil//not used//2. Assigning ValuesName ="CJH"//3. Take the valuePrint (name!)//4. Forcing unpacking is a risky operation, and if there is no value, forcing the unpacking will cause the program to crash, so first judgeifName! =Nil {print (name!)}//5. Optional Bindings/*1. The name has no value, and if there is no value, the contents of {} are not executed 2. If there is a value, the system first forces the package to name, then assigns the value to the previous name, and then executes the contents of {}.*/ifLet name =name{print (name)}
Three, type conversion. Is and as, which is similar to Iskindofclass in OC, determines whether an instance is of a certain type. As is the case of a certain type, the basic usage is as follows
Import UIKit//Use of 1.isLet array= ["CJH","ABC", A, the]let Item= array[3]ifItem isInt {print ("is an integral type")}//2.as? as! //1. Turn the nsobject into a specific type//2.as? Turn NSObject into an optional type//3.as! the nsobject into a specific type (note: If the conversion is unsuccessful, the program crashes, use caution)//2.1 Defining DictionariesLet infodict = ["name":"CJH"," Age": -,"Height":1.8]let Age= infodict[" Age"]//write one step at a separate stepifLet Age1 =Age {Let age2= Age1 as?IntifLet Age3 =age2{Print (Age3)}}//Simple notationifLet age = infodict[" Age"] as?int{print (age)}
OK, that's it.
Nevermore 16.05.12
Swift (two, tuple, optional type, type conversion)