这是Swift by Tutorials的最后一章,主要是提供一个Swift实践代码的快速查找手册,方便开发时快速查阅。
Language basics
12345678910111213141516171819202122
// variables can be updatedvarvariableNumber:Int=1variableNumber=variableNumber+1// constants cannot be updatedletconstNumber:Int=1// constNumber = constNumber + 1 <- error!// inferred typeletinferredInt=1// Swift typesletint:Int=20letdouble:Double=3.5letfloat:Float=4.5letbool:Bool=falseletstr:String="Hello Swift!"// explicit type conversionletpi=3.1415letmultiplier=2lettwoPi=pi*Double(multiplier)
forindexin1..<3{// loops with index taking values 1,2}forindexin1...3{// loops with index taking values 1,2,3}//http://stackoverflow.com/questions/32197250/using-stride-in-swift-2-0forindexin10.stride(to:20,by:2){// loops form 10 to 20 (inclusive) in steps of 2}varindex=0whileindex<5{// loops 5 timesindex++}index=0repeat{// loops 5 timesindex++}whileindex<5// if/elselettemperature=45iftemperature>60{print("It's hot!")}elseiftemperature>40{print("It's warm")}else{print("It's chilly")}
Tuples
12345678910111213141516
lettuple=(1,3,5)// inferred type (Int, Int, Int)lettuple2=(1,5.0)// inferred type (Int, Double)lettuple3:(Double,Double)=(5,6)// indexing a tupleprint(tuple.0)print(tuple.1)print(tuple.2)// a tuple with named elementsletproduct=(id:24,name:"Swift Book")print(product.name)// decomposing a tuplelet(x,y,z)=tupleprint("\(x), \(y), \(z)")// "1, 3, 5"
// empty dictionary creationletempty1=[Int:String]()letempty2=Dictionary<Int,String>()letempty3:[Int:String]=[:]// a constant dictionary with inferred typeletanimals=[24:"cat",36:"dog"]// animals[88] = "fish" <- error!// a variable dictionary with explicit typevarmutableAnimals:[Int:String]=[24:"cat",36:"dog"]mutableAnimals[55]="fish"mutableAnimals[24]="chicken"// dictionary APIanimals[24]// "cat"animals[1]// nilanimals.count// "2"mutableAnimals.removeValueForKey(24)// "chicken"// dictionary values are returned as optionalsanimals[24]!.hasPrefix("c")// true// iterationfor(key,value)inanimals{print(key)print(value)}
Tips:
Swift中的Dictionary是数值类型
Optionals
1234567891011121314151617181920212223242526272829
// an optional variablevarmaybeString:String?// defaults to nilmaybeString=nil// can be assigned a nil valuemaybeString="fish"// can be assigned a value// unwrapping an optionalifletunwrappedString=maybeString{// unwrappedString is a String rather than an optional Stringprint(unwrappedString.hasPrefix("f"))// "true"}else{print("maybeString is nil")}// forced unwrapping - will fail at runtime if the optional is nilifmaybeString!.hasPrefix("f"){print("maybeString starts with 'f'")}// optional chaining, returning an optional with the // result of hasPrefix, which is then unwrappediflethasPrefix=maybeString?.hasPrefix("f"){ifhasPrefix{print("maybeString starts with 'f'")}}// null coalescevaranOptional:Int?varcoalesced=anOptional??3// anOptional is nil, coalesced to 3
Implicitly unwrapped optionals
1234567891011
// an implicitely unwrapped optional variablevarmaybeString:String!maybeString=nilmaybeString="fish"// methods invoked directly, failing at runtime if the optional is nilifmaybeString.hasPrefix("f"){print("maybeString starts with 'f'")}else{print("maybeString does not start with an 'f'")}
letbit=Bit.Zero// a simple switch statement on an enumswitchbit{case.Zero:print("zero")case.One:print("one")}// interval matchinglettime=45switchtime{case0..<60:print("A few seconds ago")case60..<(60*4):print("A few minutes ago")default:// default required in orderprint("Ages ago!")// to be exhaustive}// tuples and value bindingsletboardLocation=(2,5)switchboardLocation{case(3,4),(3,3),(4,3),(4,4):print("central location")case(letx,lety):print("(\(x), \(y) is not in the center")}
// enum declarationenumDirection{caseNorth,South,East,West}// assignmentvardirection=Direction.Northdirection=.South// enum type inferred// switching on enumsswitchdirection{case.North:print("Going North")default:print("Going someplace else!")}// advanced enumerations - using genericsenumResult<T>{caseFailure// enumeration member with associated valuecaseSuccess(T)}// creating an instance - where the type T is an Intvarresult=Result.Success(22)// switching and extracting the associated valueswitchresult{case.Failure:print("Operation failed")case.Success(letvalue):print("Operation returned value \(value)")}
// a simple functionfuncvoidFunc(message:String){print(message);}voidFunc("Hello Swift!")// a function that returns a valuefuncmultiply(arg1:Double,arg2:Double)->Double{returnarg1*arg2}letresult=multiply(20.0,arg2:35.2)// external and default parameters namesfuncmultiplyTwo(firstfirst:Double,andSecondsecond:Double)->Double{returnfirst*second}letresult2=multiplyTwo(first:20.0,andSecond:35.2)// inout parametersfuncsquare(inoutnumber:Double){number*=number}varnumber=4.0square(&number)// number = 16// function typesletmyFunc:(Double,Double)->Double=multiplyTwo// a generic functionfuncareEqual<T:Equatable>(op1:T,op2:T)->Bool{returnop1==op2}
publicclassBaseClass{privateletid:Int// private constant propertyinit(id:Int){self.id=id}classfuncnumberOfLegs()->Int{return4;}}protocolNamedType{varname:String{get}// a property with a getter}publicclassAnimal:BaseClass,NamedType{private(set)varname:String// variable with public getter// and private settervarsize:Double=45.0// implicit internal propertypublicletfullName:String// public constant propertyinit(id:Int,name:String,fullName:String){// all properties initialized before base init invokedself.name=name;self.fullName=fullName;// super initialiser invokedsuper.init(id:id)// methods on self can now be called}}// creating an instancevaranimal=Animal(id:24,name:"cat",fullName:"Felis catus")