swift5分钟语法速记

(一)类型

常见类型

Int,String,Double,struct,enum,class,tuple//typle 元组类型//声明letsomeTuple:(Int,Int)=(10,23)//元组可以设置名称varperson=(name:"liuyw",age:30)//取值方式1person.0person.1//取值方式2person.ageperson.name//取值方式3var(personName,personAge)=personpersonNamepersonAgesomeTuple.0或者tuple.1//typealias//类型的别名关键字//函数类型func//可选类型varnum:Int?=nilvarnum1:Optional=nil//隐式解析可选varnum:Int!varnum1:ImplicitlyUnwrappedOptional//协议合成类型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=""//遍历foritem:Stringinarray1{}forbgeninarray1.enumerate(){print("元素下标:\(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"]//字典的循环for(key,value)indictionary{println("key is:\(key)value is :\(value)");}

枚举enum

//整形的枚举enumSharp:Int{caseRect=1,Circle,Star//switch中的选项可以用.表示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)//调用枚举的方法Sharp.Rect.desc()

## 结构struct

//结构//结构和类的最重要的区别就是架构是传值,类是传引用structSharp{//属性varwidth:Intvarheight:Int//方法funcarea()->Int{returnself.width*self.height;}//允许修改属性的方法前缀 mutatingmutatingfunczoomIn(){self.width+=100self.height+=100}}

## 协议

//可以被class,struct,enum实现protocolSharp{//属性varwidth:String{get}varheiht:String{getset}//方法funcarea()->Int}//swift 可选和必选协议//只能被class实现,无法给struct和enum实现@objcprotocolOptionalProtocol{//可选协议optionalfuncoptionalMethod()//必选协议funcnecessaryMethod()}

对象

classCard:NSObject{}classPerson:NSObject{//私有对象privatevar_name:String?vargender:Stringvargender1:String?//arc/*

weak 用于可空对象,unowned用于非空对象

weak 调用被释放的对象会返回nil,unowned 调用被释放的对象会出异常

建议 如果能够确定在访问时不会已被释放的话,尽量使用 unowned,如果存在被释放的可能,那就选择用 weak

*/weakvarbastFriend:Person?unownedvaridentityCard:Card//构造函数init(name:String){gender="male"identityCard=Card()super.init()//初始化。。。self.name=name}//便利构造函数convenienceinit(name:String,gender:String){self.init(name:name)self.gender=gender}//析构函数deinit{}//属性varname:String{get{return_name!}set{_name=newValue;}//可以自定newValue的名称//set(newName){//  _gender = newName//}}//观察者模式的属性//newValue 和 oldValuevarage:Int=0{willSet{}didSet{}}//方法funcsayName(){print("hello name")}//静态方法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"}()//调用//NSLog("bastFirends:%@ and friends is:[%@] ",p.bastFirends,p.friends)//下标脚本subscript(name:String)->String{get{returnself.name}set{self.name=newValue;}}}

(二)语法

流程控制

if语句

//判断是Option类是否有值iflettheStr=str2{print("ture")}

switch

//switch 数字区间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的判断letnum:Int?=nilswitchnum{casenil:println("没值")default:println("\(num!)")}

函数

//无参数funchello(){}//有参数funchello(name:String){}//有参数和返回值funchello(name:String)->String{}//多个参数funchello(name:String,age:Int){}//多个返回值funchello()->(String,Int){return(num1,num2,num3)}//可变参数funchello(name:String...){}//函数的嵌套funchello1(){funchello2(){}}//参数的默认值funchello1(msg:String="defaultMsg"){}//返回值是函数funchello()->(String->String){funchello1(name:String)->String{}returnhello1}//参数是函数funhello(msg:String,callback(Void->Void)){callback()}//函数参数是变量//若不声明var ,默认参数类型是let,就无法修改参数的值funchello(varmsg:String){msg+="hello"print(msg)}//函数参数的命名funchello(namename:String,withAgeage:Int){}funchello1(name:String,age:Int){}//调用hello(name:,withAge:)//默认的参数命名hello1(,age:)//指定的参数命名//匿名函数//{}可以作为匿名函数//例如调用上面的hello方法(参数是函数)hello("hi",{//dosthing})//有参数的匿名函数{(msg:String)->Stringinreturnmsg}//泛型参数//输入输出参数的函数funcmyswap(inoutobj1:T,inout_obj2:T){lettemp:T=obj1obj1=obj2obj2=temp}

闭包

vararray=["f","a","c","d","e"]//完整写法//{ (参数:类型) in 执行方法 return 返回值}array.sort({(s1:String,s2:String)->Boolinreturns2>s1;})//省略参数类型和括号//{ 参数$1,$2 in 执行方法 return 返回值}array.sort({s1,s2->Boolinreturns1>s2;})//省略参数类型和return关键字//{ 参数$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 > 这个关键字可以给类,结构,枚举等增加别名,也常常用于合并协议后的别名 typealias PetLike = protocol

编译标记

//MARK : //MARK -: // TODO: // FIXME:

Selector

objc里面有@Selector(),在swift可以使用 let someMethod = Selector(“someMethodName”)得到。大多数情况无需这样

funccallMe(){NSLog("this is callMe")}funccallMeWithParam(timer:NSTimer){NSLog("this is callMeWithParam,prarm is :\(timer.userInfoas!String)")}//无参数NSTimer.scheduledTimerWithTimeInterval(2,target:self,selector:"callMe",userInfo:nil,repeats:true)//带参数,不使用SelectorNSTimer.scheduledTimerWithTimeInterval(2,target:self,selector:"callMeWithParam:",userInfo:"i'm prarm",repeats:true)

扩展

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)

柯里化是一种量产类似方法的好办法,可以通过柯里化一个方法模板来避免写出很多重复代码

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)!"}()

方法调用的另一种方式

classPerson{//普通方法funchi(name:String)->String{return"hi\(name)"}//静态方法classfunchello(){NSLog("hello")}}letperson=Person()//常规方法调用person.hi("liuyanwei")Person.hello()//利用方法名调用letfuncOnPerson1=Person.hifuncOnPerson1(person)("liuyanwei")//调用静态方法letfuncOnPerson2=Person.hellofuncOnPerson2()

swift单例标准写法

classMyManager{staticprivateletsharedInstance=MyManager()classvarsharedManager:MyManager{returnsharedInstance}}

最后

此速记已经收录在ios-tips中。

ios-tips是ios开发当中常用遇到的问题和解决方法的收集,包括ios和swif。 一共包括4个部分

0_Foundation

1_UIKit

2_ThirdParty

3_Other

目前已经整理完0_Foundation,开始整理UIKit。也欢迎大家给ios-tips补充内容。

补充要求

格式是md

tips都很简短,不要涉及复杂的原理和方法

感谢收看,如果对大家有帮助,请github上follow和star,本文发布在刘彦玮的技术博客,转载请注明出处

===========

参考文章: 1. The Swift Programming Language 2.swifter

你可能感兴趣的:(swift5分钟语法速记)