Swift是什么?Swift是苹果于WWDC2014发布的编程语言,这里引用TheSwiftProgrammingLanguage的原话:SwiftisanewprogramminglanguageforiOSandOSXappsthatbuildsonthebestofCandObjective-C,withouttheconstraintsofCcompatibility.Swiftadoptssafeprogrammingpatternsandaddsmodernfeaturestomakeprogrammingeasier,moreflexibleandmorefun.Swift’scleanslate,backedbythematureandmuch-lovedCocoaandCocoaTouchframeworks,isanopportunitytoimaginehowsoftwaredevelopmentworks.Swiftisthefirstindustrial-qualitysystemsprogramminglanguagethatisasexpressiveandenjoyableasascriptinglanguage.简单的说:Swift用来写iOS和OSX程序。(估计也不会支持其它屌丝系统)Swift吸取了C和Objective-C的优点,且更加强大易用。Swift可以使用现有的Cocoa和CocoaTouch框架。Swift兼具编译语言的高性能(Performance)和脚本语言的交互性(Interactive)。Swift语言概览基本概念注:这一节的代码源自TheSwiftProgrammingLanguage中的ASwiftTour。Hello,world类似于脚本语言,下面的代码即是一个完整的Swift程序。println(Hello,world)变量与常量Swift使用var声明变量,let声明常量varmyVariable=42myVariable=50letmyConstant=42类型推导Swift支持类型推导(TypeInference),所以上面的代码不需指定类型,如果需要指定类型:letexplicitDouble:Double=70Swift不支持隐式类型转换(Implicitlycasting),所以下面的代码需要显式类型转换(Explicitlycasting):letlabel=Thewidthisletwidth=94letwidth=label+String(width)字符串格式化Swift使用\(item)的形式进行字符串格式化:letapples=3letoranges=5letappleSummary=Ihave\(apples)apples.letappleSummary=Ihave\(apples+oranges)piecesoffruit.数组和字典Swift使用[]操作符声明数组(array)和字典(dictionary):varshoppingList=[catfish,water,tulips,bluepaint]shoppingList[1]=bottleofwatervaroccupations=[Malcolm:Captain,Kaylee:Mechanic,]occupations[Jayne]=PublicRelations一般使用初始化器(initializer)语法创建空数组和空字典:letemptyArray=String[]()letemptyDictionary=DictionaryString,Float()如果类型信息已知,则可以使用[]声明空数组,使用[:]声明空字典。控制流概览Swift的条件语句包含if和switch,循环语句包含for-in、for、while和do-while,循环/判断条件不需要括号,但循环/判断体(body)必需括号:letindividualScores=[75,43,103,87,12]varteamScore=0forscoreinindividualScores{ifscore50{teamScore+=3}else{teamScore+=1}}可空类型结合if和let,可以方便的处理可空变量(nullablevariable)。对于空值,需要在类型声明后添加?显式标明该类型可空。varoptionalString:String?=HellooptionalString==nilvaroptionalName:String?=JohnAppleseedvargretting=Hello!ifletname=optionalName{gretting=Hello,\(name)}灵活的switchSwift中的switch支持各种各样的比较操作:letvegetable=redpepperswitchvegetable{casecelery:letvegetableComment=Addsomeraisinsandmakeantsonalog.casecucumber,watercress:letvegetableComment=Thatwouldmakeagoodteasandwich.caseletxwherex.hasSuffix(pepper):letvegetableComment=Isitaspicy\(x)?default:letvegetableComment=Everythingtastesgoodinsoup.}其它循环for-in除了遍历数组也可以用来遍历字典:letinterestingNumbers=[Prime:[2,3,5,7,11,13],Fibonacci:[1,1,2,3,5,8],Square:[1,4,9,16,25],]varlargest=0for(kind,numbers)ininterestingNumbers{fornumberinnumbers{ifnumberlargest{largest=number}}}largestwhile循环和do-while循环:varn=2whilen100{n=n*2}nvarm=2do{m=m*2}whilem100mSwift支持传统的for循环,此外也可以通过结合..(生成一个区间)和for-in实现同样的逻辑。varfirstForLoop=0foriin0..3{firstForLoop+=i}firstForLoopvarsecondForLoop=0forvari=0;i3;++i{secondForLoop+=1}secondForLoop注意:Swift除了..还有...:..生成前闭后开的区间,而...生成前闭后闭的区间。函数和闭包函数Swift使用func关键字声明函数:funcgreet(name:String,day:String)-String{returnHello\(name),todayis\(day).}greet(Bob,Tuesday)通过元组(Tuple)返回多个值:funcgetGasPrices()-(Double,Double,Double){return(3.59,3.69,3.79)}getGasPrices()支持带有变长参数的函数:funcsumOf(numbers:Int...)-Int{varsum=0fornumberinnumbers{sum+=number}returnsum}sumOf()sumOf(42,597,12)函数也可以嵌套函数:funcreturnFifteen()-Int{vary=10funcadd(){y+=5}add()returny}returnFifteen()作为头等对象,函数既可以作为返回值,也可以作为参数传递:funcmakeIncrementer()-(Int-Int){funcaddOne(number:Int)-Int{return1+number}returnaddOne}varincrement=makeIncrementer()increment(7)funchasAnyMatches(list:Int[],condition:Int-Bool)-Bool{foriteminlist{ifcondition(item){returntrue}}returnfalse}funclessThanTen(number:Int)-Bool{returnnumber10}varnumbers=[20,19,7,12]hasAnyMatches(numbers,lessThanTen)闭包本质来说,函数是特殊的闭包,Swift中可以利用{}声明匿名闭包:numbers.map({(number:Int)-Intinletresult=3*numberreturnresult})当闭包的类型已知时,可以使用下面的简化写法:numbers.map({numberin3*number})此外还可以通过参数的位置来使用参数,当函数最后一个参数是闭包时,可以使用下面的语法:sort([1,5,3,12,2]){$0$1}类和对象创建和使用类Swift使用class创建一个类,类可以包含字段和方法:classShape{varnumberOfSides=0funcsimpleDescription()-String{returnAshapewith\(numberOfSides)sides.}}创建Shape类的实例,并调用其字段和方法。varshape=Shape()shape.numberOfSides=7varshapeDescription=shape.simpleDescription()通过init构建对象,既可以使用self显式引用成员字段(name),也可以隐式引用(numberOfSides)。classNamedShape{varnumberOfSides:Int=0varname:Stringinit(name:String){self.name=name}funcsimpleDescription()-String{returnAshapewith\(numberOfSides)sides.}}使用deinit进行清理工作。继承和多态Swift支持继承和多态(override父类方法):classSquare:NamedShape{varsideLength:Doubleinit(sideLength:Double,name:String){self.sideLength=sideLengthsuper.init(name:name)numberOfSides=4}funcarea()-Double{returnsideLength*sideLength}overridefuncsimpleDescription()-String{returnAsquarewithsidesoflength\(sideLength).}}lettest=Squar