所在的位置: swift >> swift优势 >> Swift57新特性

Swift57新特性

网络编辑求职招聘QQ群 http://www.gpitp.gd.cn/new/20211001/95866.html

Swift5.7内置于Xcode14,重点增加了如下几个与实际开发相关的新特性。

简化的iflet/guardlet语法

letname:String?="zhangsan"print(name)//Optional("zhangsan")//Swift5.7之前//ifletifletname=name{print(name)//zhangsan}//Swift5.7之后//ifletifletname{print(name)//zhangsan}funcmethod(name:String?,age:Int?){//Swift5.7之前//guardletguardletname=nameelse{return}//Swift5.7之后//guardletguardletage=ageelse{return}}增强的闭包类型推断

letarray:[String]=["1","2","3","4","5"]//Swift5.7之前letnewArray1=array.map{str-IntinInt(str)??0}print(newArray1)//[1,2,3,4,5]//Swift5.7之后letnewArray2=array.map{strinInt(str)??0}print(newArray2)//[1,2,3,4,5]正则表达式

引入了新的正则类型Regex。

增加了通过/.../创建正则表达式的功能。

增加了许多基于正则表达式的String处理方法。

letmessage="Thisisaregextestcase"do{//字符串中搜索regexletregex=tryRegex("[a-z]regex")//范围print(message.ranges(of:regex))//替换print(message.replacing(regex,with:"正则表达式"))}catch{print("FailedtocreateRegex")}///.../创建正则表达式,查找数字并替换print(message.replacing(/(\d+)/,with:"一二三四五六七八九"))函数参数与返回类型支持不透明结果类型

importSwiftUI//参数与返回值支持不透明结果类型//some后面是一个协议funcgetSomeView(username:someStringProtocol,image:String)-(someView,someView){return(Text(username),Image(systemName:image))}structContentView:View{letsomeView:(someView,someView)=getSomeView(username:"zhangsan",image:"heart")varbody:someView{VStack(spacing:10){someView.0.font(.title)someView.1.foregroundStyle(.tint)}}}新的时间表示法

Clock:表示一种测量时间流逝的方式。又分为2种。

ContinuousClock:系统处于睡眠状态时也会记录时间。

SuspendingClock:系统处于睡眠状态时不会记录时间。

Instant:表示一个精准的瞬间时间。

Duration:表示2个Instant之间的时间间隔。

//当前时间+3秒ContinuousClock.Instant.now+Duration.seconds(3)//当前时间+50毫秒ContinuousClock.Instant.now+Duration.microseconds(50)//应用于ConcurrencytryawaitTask.sleep(until:.now+.seconds(1),clock:.suspending)tryawaitTask.sleep(until:.now+.seconds(1),tolerance:.seconds(0.5),clock:.continuous)//异步函数funcdoSomeAsyncWork()asyncthrows{tryawaitTask.sleep(until:.now+.seconds(1),clock:.continuous)}//SuspendingClockletsuspendingClock=SuspendingClock()//测量letelapsedOne=tryawaitsuspendingClock.measure{tryawaitdoSomeAsyncWork()}//ContinuousClockletcontinuousClock=ContinuousClock()//测量letelapsedTwo=tryawaitcontinuousClock.measure{tryawaitdoSomeAsyncWork()}顶级代码支持Concurrency

Swift5.7之前Concurrency的代码必须放入函数或者Task中,不能出现在顶级代码中,Swift5.7之后没有这个限制。因此在macOS的命令行项目中可以书写以下代码。

leturl=URL(string:"


转载请注明:http://www.aierlanlan.com/grrz/643.html