(一)類型
常見類型
Int,String,Double,struct,enum,class,tuple//typle 元組類型//聲明letsomeTuple:(Int,Int)=(10,23)//元組可以設(shè)置名稱varperson=(name:"liuyw",age:30)//取值方式1person.0person.1//取值方式2person.ageperson.name//取值方式3var(personName,personAge)=personpersonNamepersonAgesomeTuple.0或者tuple.1//typealias//類型的別名關(guān)鍵字//函數(shù)類型func//可選類型varnum:Int?=nilvarnum1:Optional=nil//隱式解析可選varnum:Int!varnum1:ImplicitlyUnwrappedOptional//協(xié)議合成類型varsomeProtocol:protocol
Array
//聲明vararray1:[String]=["0","1","2","3"]vararray=[String]()//修改值array1+=["4","5"]array1[1...3]=["a","b","c","d","e"]//array1.append//array1.removeAtIndex()//array1.insert(, atIndex:)//獲取值print(array1)print(array1[0])print(array1.last)print(array1.first)varstr:String=""http://遍歷foritem:Stringinarray1{}forbgeninarray1.enumerate(){print("元素下標(biāo):\(bgen.0)元素值:\(bgen.1)")}
dictionary
//聲明vardic:Dictionary=["name":"liu","age":"30"]vardic1=Dictionary()//修改值dic["name"]="liuyanwei"dic["name1"]="liuyanwei1"dic.updateValue("liuyw",forKey:"name")//返回原值dic1.indexForKey("name1")dic.removeValueForKey("name")//獲取值dic["name"]//字典的循環(huán)for(key,value)indictionary{println("key is:\(key)value is :\(value)");}
枚舉enum
//整形的枚舉enumSharp:Int{caseRect=1,Circle,Star//switch中的選項(xiàng)可以用.表示funcdesc()->String{switchself{case.Rect:return"this is rect"case.Circle:return"this is circle"case.Star:return"this is star"}}}//enum的值Sharp.RawValue(1)//調(diào)用枚舉的方法Sharp.Rect.desc()
## 結(jié)構(gòu)struct
//結(jié)構(gòu)//結(jié)構(gòu)和類的最重要的區(qū)別就是架構(gòu)是傳值,類是傳引用structSharp{//屬性varwidth:Intvarheight:Int//方法funcarea()->Int{returnself.width*self.height;}//允許修改屬性的方法前綴 mutatingmutatingfunczoomIn(){self.width+=100self.height+=100}}
## 協(xié)議
//可以被class,struct,enum實(shí)現(xiàn)protocolSharp{//屬性varwidth:String{get}varheiht:String{getset}//方法funcarea()->Int}//swift 可選和必選協(xié)議//只能被class實(shí)現(xiàn),無法給struct和enum實(shí)現(xiàn)@objcprotocolOptionalProtocol{//可選協(xié)議optionalfuncoptionalMethod()//必選協(xié)議funcnecessaryMethod()}
對象
classCard:NSObject{}classPerson:NSObject{//私有對象privatevar_name:String?vargender:Stringvargender1:String?//arc/*
weak 用于可空對象,unowned用于非空對象
weak 調(diào)用被釋放的對象會返回nil,unowned 調(diào)用被釋放的對象會出異常
建議 如果能夠確定在訪問時不會已被釋放的話,盡量使用 unowned,如果存在被釋放的可能,那就選擇用 weak
*/weakvarbastFriend:Person?unownedvaridentityCard:Card//構(gòu)造函數(shù)init(name:String){gender="male"identityCard=Card()super.init()//初始化。。。self.name=name}//便利構(gòu)造函數(shù)convenienceinit(name:String,gender:String){self.init(name:name)self.gender=gender}//析構(gòu)函數(shù)deinit{}//屬性varname:String{get{return_name!}set{_name=newValue;}//可以自定newValue的名稱//set(newName){//? _gender = newName//}}//觀察者模式的屬性//newValue 和 oldValuevarage:Int=0{willSet{}didSet{}}//方法funcsayName(){print("hello name")}//靜態(tài)方法staticfuncsay(){print("hello")}//類方法classfuncsay1(){print("hello1")}//方法重載overridefunccopy()->AnyObject{return""}//懶屬性//兩種方式,方法加載和閉包加載lazyvarfriends:[String]=self.findfriends()funcfindfriends()->[String]{return["bob","bill","jobs"]}lazyvarbastFirends:String={print(" print bastFirends")return"liuyanwei"}()//調(diào)用//NSLog("bastFirends:%@ and friends is:[%@] ",p.bastFirends,p.friends)//下標(biāo)腳本subscript(name:String)->String{get{returnself.name}set{self.name=newValue;}}}
(二)語法
流程控制
if語句
//判斷是Option類是否有值iflettheStr=str2{print("ture")}
switch
//switch 數(shù)字區(qū)間varcondition1=888_888_888;switchcondition1{case-999_999...38:print("case1");case40...88:print("case2");case100...188:print("case3");case200...999_999_999_999:print("case3");default:break;}//switch? 元組varcondition2=(100,88);switchcondition2{case(-99999...0,-99999...0),(40...88,0..<100):print("case1")//匹配多個條件caselet(_,y):print(y);fallthrough// 值綁定,fallthrough 墜落下一個條件case(_,0...100):print("case3");// “_” 匹配所有default:break;}//switch 值綁定和where語句varcondition3=100switchcondition3{caseletiwherei<50:print("case1")caseletiwherei<120&&i>50:print("case2")default:break;}//switch 枚舉enumBarCode{caseUPCA(Int,Int,Int)caseQRCode(String)}varcondition4=BarCode.UPCA(10,5,2)switchcondition4{caselet.UPCA(a,b,c):print("a:\(a)|b:\(b)|c:\(c)")case.QRCode:print("case:2")//? ? default: break}//對option的判斷l(xiāng)etnum:Int?=nilswitchnum{casenil:println("沒值")default:println("\(num!)")}
函數(shù)
//無參數(shù)funchello(){}//有參數(shù)funchello(name:String){}//有參數(shù)和返回值funchello(name:String)->String{}//多個參數(shù)funchello(name:String,age:Int){}//多個返回值funchello()->(String,Int){return(num1,num2,num3)}//可變參數(shù)funchello(name:String...){}//函數(shù)的嵌套funchello1(){funchello2(){}}//參數(shù)的默認(rèn)值funchello1(msg:String="defaultMsg"){}//返回值是函數(shù)funchello()->(String->String){funchello1(name:String)->String{}returnhello1}//參數(shù)是函數(shù)funhello(msg:String,callback(Void->Void)){callback()}//函數(shù)參數(shù)是變量//若不聲明var ,默認(rèn)參數(shù)類型是let,就無法修改參數(shù)的值funchello(varmsg:String){msg+="hello"print(msg)}//函數(shù)參數(shù)的命名funchello(namename:String,withAgeage:Int){}funchello1(name:String,age:Int){}//調(diào)用hello(name:,withAge:)//默認(rèn)的參數(shù)命名hello1(,age:)//指定的參數(shù)命名//匿名函數(shù)//{}可以作為匿名函數(shù)//例如調(diào)用上面的hello方法(參數(shù)是函數(shù))hello("hi",{//dosthing})//有參數(shù)的匿名函數(shù){(msg:String)->Stringinreturnmsg}//泛型參數(shù)//輸入輸出參數(shù)的函數(shù)funcmyswap(inoutobj1:T,inout_obj2:T){lettemp:T=obj1obj1=obj2obj2=temp}
閉包
vararray=["f","a","c","d","e"]//完整寫法//{ (參數(shù):類型) in 執(zhí)行方法 return 返回值}array.sort({(s1:String,s2:String)->Boolinreturns2>s1;})//省略參數(shù)類型和括號//{ 參數(shù)$1,$2 in 執(zhí)行方法 return 返回值}array.sort({s1,s2->Boolinreturns1>s2;})//省略參數(shù)類型和return關(guān)鍵字//{ 參數(shù)$1,$2 in 返回值}array.sort({s1,s2->Boolins1(()->Int){vari=0;return{()->Intinreturn++i}}//測試使用vartouch=count()touch()//1touch()//2touch()//3touch()//4
異常處理
enumAwfulError:ErrorType{caseBadcaseWorsecaseTerrible}funchello()throws{throwAwfulError.Bad}do{tryhello()print("final")}catchAwfulError.Bad{print("Bad")}catchAwfulError.Worse{print("Worse")}catchAwfulError.Terrible{print("Terrible")}catch{print("all error")}
## 斷言
assert(assert()assert(,)assertionFailure()assertionFailure()
## typealias > 這個關(guān)鍵字可以給類,結(jié)構(gòu),枚舉等增加別名,也常常用于合并協(xié)議后的別名 typealias PetLike = protocol
編譯標(biāo)記
//MARK : //MARK -: // TODO: // FIXME:
Selector
objc里面有@Selector(),在swift可以使用 let someMethod = Selector(“someMethodName”)得到。大多數(shù)情況無需這樣
funccallMe(){NSLog("this is callMe")}funccallMeWithParam(timer:NSTimer){NSLog("this is callMeWithParam,prarm is :\(timer.userInfoas!String)")}//無參數(shù)NSTimer.scheduledTimerWithTimeInterval(2,target:self,selector:"callMe",userInfo:nil,repeats:true)//帶參數(shù),不使用SelectorNSTimer.scheduledTimerWithTimeInterval(2,target:self,selector:"callMeWithParam:",userInfo:"i'm prarm",repeats:true)
擴(kuò)展
extensionPerson{funcanotherHello(){NSLog("another hello")}}
## OptionSetType
OptionSetType是NSOption在swift的替代
publicstructUIViewAutoresizing:OptionSetType{publicinit(rawValue:UInt)publicstaticvarNone:UIViewAutoresizing{get}publicstaticvarFlexibleLeftMargin:UIViewAutoresizing{get}publicstaticvarFlexibleWidth:UIViewAutoresizing{get}publicstaticvarFlexibleRightMargin:UIViewAutoresizing{get}publicstaticvarFlexibleTopMargin:UIViewAutoresizing{get}publicstaticvarFlexibleHeight:UIViewAutoresizing{get}publicstaticvarFlexibleBottomMargin:UIViewAutoresizing{get}}//使用,選擇多個[FlexibleLeftMargin,FlexibleWidth]
(三)高級
柯里化 (Currying)
柯里化是一種量產(chǎn)類似方法的好辦法,可以通過柯里化一個方法模板來避免寫出很多重復(fù)代碼
funcaddTwoNumbers(a:Int)(num:Int)->Int{returna+num}letaddToFour=addTwoNumbers(4)// addToFour 是一個 Int -> Intletresult=addToFour(num:6)// result = 10
封裝局部變量
封裝局部變量可以減少變量之間的沖突
varstr:String={//局部變量被封裝letstr1="hello",str2="world"return"\(str1)\(str2)!"}()
方法調(diào)用的另一種方式
classPerson{//普通方法funchi(name:String)->String{return"hi\(name)"}//靜態(tài)方法classfunchello(){NSLog("hello")}}letperson=Person()//常規(guī)方法調(diào)用person.hi("liuyanwei")Person.hello()//利用方法名調(diào)用letfuncOnPerson1=Person.hifuncOnPerson1(person)("liuyanwei")//調(diào)用靜態(tài)方法letfuncOnPerson2=Person.hellofuncOnPerson2()
swift單例標(biāo)準(zhǔn)寫法
classMyManager{staticprivateletsharedInstance=MyManager()classvarsharedManager:MyManager{returnsharedInstance}}
最后
此速記已經(jīng)收錄在ios-tips中。
ios-tips是ios開發(fā)當(dāng)中常用遇到的問題和解決方法的收集,包括ios和swif。 一共包括4個部分
0_Foundation
1_UIKit
2_ThirdParty
3_Other
目前已經(jīng)整理完0_Foundation,開始整理UIKit。也歡迎大家給ios-tips補(bǔ)充內(nèi)容。
補(bǔ)充要求
格式是md
tips都很簡短,不要涉及復(fù)雜的原理和方法
感謝收看,如果對大家有幫助,請github上follow和star,本文發(fā)布在劉彥瑋的技術(shù)博客,轉(zhuǎn)載請注明出處
===========
參考文章: 1. The Swift Programming Language 2.swifter