一,Swift 介绍
Swift 是一门由苹果公司于2014年WWDC 苹果开发者大会上发布的新的开发语言,可与Objective-C*共同运行于Mac OS和iOS平台,用于搭建基于苹果平台的应用程序。
其优点:Swift 有类似 Python 的易用性,又有较强的运行效率。既有Objective C的运行时动态支持,和基于编译期引用计数的内存管理模型,又具备Ruby灵活优雅的语法,C++的严格编译期检查、Javascript和Ruby的closure。Swift还支持与Objective C 混编,完美支持IOS/Mac 的SDK。
历史版本:
Swift 4.1 is available as part of Xcode 9.3.
Swift 4.0.3
Swift 4.0.2
Swift 4.0
Swift 3.1.1
Swift 3.1
Swift 3.0.2
Swift 3.0.1
Swift 3.0
Swift 2.2.1
Swift 2.2
二,简单示例代码
`print(“Hello, world!”)`
1,变量和常量
使用 let来声明一个常量,用 var来声明一个变量。常量的值在编译时并不要求已知,但是你必须为其赋值一次。这意味着你可以使用常量来给一个值命名,然后一次定义多次使用。
```
var myVariable = 42
myVariable = 50
let myConstant = 42
```
2,控制流
使用 if和 switch来做逻辑判断,使用 for-in, for, while,以及 repeat-while来做循环。使用圆括号把条件或者循环变量括起来不再是强制的了,不过仍旧需要使用花括号来括住代码块。
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
ifscore >50{
teamScore +=3
}else{
teamScore +=1
}
}
print(teamScore)
3,函数和闭包
使用 func来声明一个函数。通过在名字之后在圆括号内添加一系列参数来调用这个方法。使用 ->来分隔形式参数名字类型和函数返回的类型。
func greet(person: String, day: String) -> String {
return"Hello\(person), today is\(day)."
}
greet(person: “Bob”, day: “Tuesday”)
4,对象和类
通过在 class后接类名称来创建一个类。在类里边声明属性与声明常量或者变量的方法是相同的,唯一的区别的它们在类环境下。同样的,方法和函数的声明也是相同的写法。
class Shape {
varnumberOfSides =0
funcsimpleDescription()->String{
return"A shape with\(numberOfSides)sides."
}
}
5,枚举和结构体
使用 enum来创建枚举,类似于类和其他所有的命名类型,枚举也能够包含方法。
enum Rank: Int {
caseace =1
casetwo, three, four, five, six, seven, eight, nine, ten
casejack, queen, king
funcsimpleDescription()->String{
switchself{
case.ace:
return"ace"
case.jack:
return"jack"
case.queen:
return"queen"
case.king:
return"king"
default:
returnString(self.rawValue)
}
}
}
let ace = Rank.ace
let aceRawValue = ace.rawValue
6,协议和扩展
使用 protocol来声明协议。
protocol ExampleProtocol {
varsimpleDescription:String{get}
mutatingfuncadjust()
}
类,枚举以及结构体都兼容协议。
class SimpleClass: ExampleProtocol {
var simpleDescription:String="A very simple class."
var anotherProperty:Int=69105
funcadjust(){
simpleDescription +=" Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
struct SimpleStructure: ExampleProtocol {
varsimpleDescription:String="A simple structure"
mutatingfuncadjust(){
simpleDescription +=" (adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
7,错误处理
你可以用任何遵循 Error协议的类型来表示错误。
enum PrinterError: Error {
caseoutOfPaper
casenoToner
caseonFire
}
使用 throw来抛出一个错误并且用 throws来标记一个可以抛出错误的函数。如果你在函数里抛出一个错误,函数会立即返回并且调用函数的代码会处理错误。
func send(job: Int, toPrinter printerName: String) throws -> String {
ifprinterName =="Never Has Toner"{
throwPrinterError.noToner
}
return"Job sent"
}
有好几种方法来处理错误。一种是使用 do-catch。在 do代码块里,你用 try来在能抛出错误的函数前标记。在catch代码块,错误会自动赋予名字 error,如果你不给定其他名字的话。
do {
let printerResponse = try send(job:1040, toPrinter:"Bi Sheng")
print(printerResponse)
} catch {
print(error)
}
8,泛型
把名字写在尖括号里来创建一个泛型方法或者类型。
func makeArray(repeating item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in 0..
result.append(item)
}
return result
}
makeArray(repeating: “knock”, numberOfTimes:4)
你可以从函数和方法同时还有类,枚举以及结构体创建泛型。
// Reimplement the Swift standard library’s optional type
enum OptionalValue {
casenone
casesome(Wrapped)
}
var possibleInteger: OptionalValue = .none
possibleInteger = .some(100)
在类型名称后紧接 where来明确一系列需求——比如说,来要求类型实现一个协议,要求两个类型必须相同,或者要求类必须继承自特定的父类。
func anyCommonElements(_ lhs: T, _ rhs: U) -> Bool
where T.Iterator.Element: Equatable, T.Iterator.Element== U.Iterator.Element{
forlhsIteminlhs {
forrhsIteminrhs {
iflhsItem == rhsItem {
returntrue
}
}
}
returnfalse
}
anyCommonElements([1, 2, 3], [3])
三、学习及参考资料
https://developer.apple.com/swift/resources/ // Xcode 9 + Swift 4 下载
1,Apple 官方Swift 学习指南(英文) The Swift Programming Language (Swift 4.1)
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1
2,一份翻译比较完整的中文版Swift 学习指南
https://www.cnswift.org/
3,Swift 评价:
https://www.zhihu.com/question/24002984
4,一个Objective C 代码 转 Swift 代码的在线网站
https://objectivec2swift.com/#/converter/
其他参考及学习资料:
https://www.jianshu.com/p/f35514ae9c1a
https://www.jianshu.com/p/805be373eded
https://www.jianshu.com/p/563738348597
https://swift.org/download/#releases
https://baike.baidu.com/item/SWIFT/14080957?fr=aladdin
https://www.jianshu.com/p/69e257a29587?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation
https://www.jianshu.com/p/46c59c647b6e
网友评论