Swift is a new programming language for iOS and OS X apps that builds on the best of C and Objective-C, without the constraints of C compatibility.html
Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible and more fun.web
Swift’s clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to imagine how software development works.express
Swift is the first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language.編程
letlabel="The width is "letwidth=94letwidth=label+String(width)
字符串格式化
Swift使用\(item)的形式進行字符串格式化:
1234
letapples=3letoranges=5letappleSummary="I have \(apples) apples."letappleSummary="I have \(apples + oranges) pieces of fruit."
數組和字典
Swift使用[]操做符聲明數組(array)和字典(dictionary):
12345678
varshoppingList=["catfish","water","tulips","blue paint"]shoppingList[1]="bottle of water"varoccupations=["Malcolm":"Captain","Kaylee":"Mechanic",]occupations["Jayne"]="Public Relations"
letvegetable="red pepper"switchvegetable{case"celery":letvegetableComment="Add some raisins and make ants on a log."case"cucumber","watercress":letvegetableComment="That would make a good tea sandwich."caseletxwherex.hasSuffix("pepper"):letvegetableComment="Is it a spicy \(x)?" default:letvegetableComment="Everything tastes good in soup."}
classNamedShape{varnumberOfSides:Int=0varname:Stringinit(name:String){self.name=name}funcsimpleDescription()->String{return"A shape with \(numberOfSides) sides."}}
使用deinit進行清理工做。
繼承和多態
Swift支持繼承和多態(override父類方法):
1234567891011121314151617181920
classSquare:NamedShape{varsideLength:Doubleinit(sideLength:Double,name:String){self.sideLength=sideLengthsuper.init(name:name)numberOfSides=4}funcarea()->Double{returnsideLength*sideLength}overridefuncsimpleDescription()->String{return"A square with sides of length \(sideLength)."}}lettest=Square(sideLength:5.2,name:"my test square")test.area()test.simpleDescription()
classEquilateralTriangle:NamedShape{varsideLength:Double=0.0init(sideLength:Double,name:String){self.sideLength=sideLengthsuper.init(name:name)numberOfSides=3}varperimeter:Double{get{return3.0*sideLength}set{sideLength=newValue/3.0}}overridefuncsimpleDescription()->String{return"An equilateral triagle with sides of length \(sideLength)."}}vartriangle=EquilateralTriangle(sideLength:3.1,name:"a triangle")triangle.perimetertriangle.perimeter=9.9triangle.sideLength
注意:賦值器(setter)中,接收的值被本身主動命名爲newValue。
willSet和didSet
EquilateralTriangle的構造器進行了例如如下操做:
爲子類型的屬性賦值。
調用父類型的構造器。
改動父類型的屬性。
假設不需要計算屬性的值。但需要在賦值先後進行一些操做的話,使用willSet和didSet:
1234567891011121314151617181920
classTriangleAndSquare{vartriangle:EquilateralTriangle{willSet{square.sideLength=newValue.sideLength}}varsquare:Square{willSet{triangle.sideLength=newValue.sideLength}}init(size:Double,name:String){square=Square(sideLength:size,name:name)triangle=EquilateralTriangle(sideLength:size,name:name)}}vartriangleAndSquare=TriangleAndSquare(size:10,name:"another test shape")triangleAndSquare.square.sideLengthtriangleAndSquare.square=Square(sideLength:50,name:"larger square")triangleAndSquare.triangle.sideLength
enumServerResponse{caseResult(String,String)caseError(String)}letsuccess=ServerResponse.Result("6:00 am","8:09 pm")letfailure=ServerResponse.Error("Out of cheese.")switchsuccess{caselet.Result(sunrise,sunset):letserverResponse="Sunrise is at \(sunrise) and sunset is at \(sunset)."caselet.Error(error):letserverResponse="Failure... \(error)"}
結構
Swift使用structkeyword建立結構。
結構支持構造器和方法這些類的特性。
結構和類的最大差異在於:結構的實例按值傳遞(passed by value)。而類的實例按引用傳遞(passed by reference)。
123456789
structCard{varrank:Rankvarsuit:SuitfuncsimpleDescription()->String{return"The \(rank.simpleDescription()) of \(suit.simpleDescription())"}}letthreeOfSpades=Card(rank:.Three,suit:.Spades)letthreeOfSpadesDescription=threeOfSpades.simpleDescription()
classSimpleClass:ExampleProtocol{varsimpleDescription:String="A very simple class."varanotherProperty:Int=69105funcadjust(){simpleDescription+=" Now 100% adjusted."}}vara=SimpleClass()a.adjust()letaDescription=a.simpleDescriptionstructSimpleStructure:ExampleProtocol{varsimpleDescription:String="A simple structure"mutatingfuncadjust(){simpleDescription+=" (adjusted)"}}varb=SimpleStructure()b.adjust()letbDescription=b.simpleDescription
// Reimplement the Swift standard library's optional typeenumOptionalValue<T>{caseNonecaseSome(T)}varpossibleInteger:OptionalValue<Int>=.NonepossibleInteger=.Some(100)