Swift Learning (三)

Type Aliases 类型别名

关键字:typealias

1
2
typealias aa = UInt16
var min = aa.min // 0

英文

  1. Conditional statements such as the if statement are covered in more detail in Control Flow.

be covered in :用……填满,表动作
be covered with:被……覆盖

  1. Swift’s type safety prevents non-Boolean values from being substituted for Bool

A be substituted for B :A 替代 B

Booleans 注:Boolean 是 swift 的基本类型

swift 类型安全,bool 值无法被非 bool 值替代

1
2
3
4
let i = 1
if i {
// 编译器报错
}

英文

concise 简明的
prevents 预防

Tuples 元祖

1
let http404Error = (404, "Not Found")

其类型可以描述为:(int , String)

分解一个元祖:

1
2
3
4
5
6
let (statusCode, statusMessage) = http404Error

print("The status code is \(statusCode)")
// print "The status code is 404\n"
print("The status message is \(statusMessage)")
// print "The status message is Not Found\n"
  • 只需要获取元祖中的某一个值
1
2
3
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// print "The status code is 404\n"
  • 使用索引访问元祖内单独元素的值
1
2
3
4
5
let (justTheStatusCode, _) = http404Error
print("The status code is \(http404Error.0)")
// print "The status code is 404\n"
print("The status message is \(http404Error.1)")
// print "The status message is Not Found\n"
  • 在定义元祖时命元祖中单独的元素
1
let http200Status = (statusCode: 200, description: "OK")

这样的话,你可以直接通过元素的名字来访问元素的值 http200Status.statusCode

注意:

元祖用于临时的值得关联,但并不适合创建一个复杂的数据结构,如果你的数据结构超过了临时变量组合,则需要使用类和结构体。

英文

permutation 序列

decompose 分解

Alternatively, the increasingly visible gap between rich and poor may breed resentment

alternatively 另外

retrieve 寻回,找回 用于 网站网址 查询 相当于 search

distinct 截然不同的

outcome 结果

Optionals 可选类型

这一概念在 C 或者 OC 中并不存在,OC 可以在方法中返回 nil,或者其他值,但是这一特性无法在结构体和枚举中使用,swift 可选类型让你标识任何类型的值缺失,而不需要特殊的常量。

example

将 string 类型的值转化为 int 类型,可能会出现 nil,因为不是所有的 string 都能转化为 int 类型。

1
2
3
4
5

let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)

// convertedNumber is type "Int?" or "optional Int"

由于转化可能失败,所以返回值为 Int?,包含可选的类型,表示值要么是 Int 值,要么没有值。

英文

concept 概念

assumes 假定

cope with 成功应对

nil

你可以通过 给一个可选类型赋值 nil 来设置其为值缺失状态

1
2
3
var serverResponseCode: Int? = 404
serverResponseCode = nil
// serverResponseCode now contains no value

如果你定义了一个可选变量,但是没有提供一个默认值,则变量将自动赋值为 nil

注意

swift 的 nil 和 OC 的 nil 不一样,在 OC 中,nil 是一个指向不存在的对象的指针。在 swift 中,代表一个确定的类型的值缺失。任何可选类型都可以被赋值 nil,而不仅仅是对象类型。

英文

appropriate 适当的,恰当的

If Statements and Forced Unwrapping If语句强制解绑(主要指可选类型)

我们可以用 if 语句找出是否一个可选变量包含有值,通过和 nil 进行比较。

比如:

1
2
3
4
5
var serverResponseCode: Int? = 404

if serverResponseCode != nil {
print("1") // print 1
}

如果你很清楚一个可选值一定有值,你可以通过在其后加 “!” 。如果这样,将相当于下面的语句:

1
2
3
if serverResponseCode != nil {
print("convertedNumber has an integer value of \(convertedNumber!).") // print 1
}

注意:

使用 ! 访问不存在的可选值会导致 runtime error,在使用 ! 之前,确保可选值是有值的 橙色

Optional Binding 可选绑定

1
2
3
if let constanName = someOptional {
statements
}
1
2
3
if let firstNumber = Int("4"), secondNumber = Int("42") where firstNumber < secondNumber {
print("11")
}

英文

extract 取出,摘录

Implicitly Unwrapped Optionals

1
2
3
4
5
let prossibleString: String? = "An optional string."
let forcedString: String = prossibleString! // requres an !

let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // no need for an !

注意

如果一个值在他的声明周期内部始终不确定是否为 nil,请使用可选类型。 橙色

英文

assumed 假定,假设

Error Handling 异常处理

关键字 : guard 红色

在 swift 中,使用枚举建立属于自己的异常类型,你只要在你的枚举中确认新的 ErrorType。

1
2
3
4
enum MyError : ErrorType {
case NotExist
case OutOfRange
}

how to Throws 如何抛出异常

具体见:Swift 中的异常处理

英文

encounter 遇到,遭遇到

In contrast to 对比,对照

Assertions 断言

Debugging with Assertions

断言机制是在 runtime 时,你如果认为这个条件一定成立,则使用 assert 来通过编译器的编译,代码得以运行,但一旦运行时检测到被你 assert 的 bool 值不是你所认为的。则程序会崩溃。

断言机制可以让你提供一个适合的 debug 消息。

使用如下方法: assert(_:file:line:)

1
2
3
let age = -3
assert(age >= 0, "A person's age canot be less than zero")
// this causes the assertion to trigger, because age is not >= 0

assertion 消息可以省略: assert(age >= 0)

注意:断言机制无法使用在 release 环境下

操作符号

swift 与 OC 不同的地方:

字符串拼接

1
"hello , " + "world" // equals "hellow , world"

求余符号的负数 和 小数处理:

1
2
3
4
-9 % 4 // equals -1
- 9 = (4 * 2) + (-1)
8 % 2.5 // equals 0.5
8 = 2.5 * 3 + 0.5

判断两个字符串是否相等:

1
2
3
4
5
6
7
8
let name = "world"
if name == "world" {
print("hello, world")
} else {
print("I'm sorry \(name), but I don't recognize you")
}

// prints "hello, world", because name is indeed equal to "world"

三目操作符

三目操作符的小变化源于 swift 新加入的可选类型

1
2
3
var a : Int?
let b = a != nil ? a! : 2
print(b)

swift 新增:

1
2
3
4
5
6
7
8
let defaultColorName = "red"
var userDefinedColorName: String? // defaults to nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"

userDefinedColorName = "green"
colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is not nil, so colorNameToUse is set to "green"

Range Operators 范围操作符

Swift 包含两个操作符

  1. 闭集范围操作符(a…b),从 a 到 b,包含 a 和 b。值不能超过 b。
  2. 开集范围操作符(a..<b),从 a 到 b,但是不包含 b。
文章作者: Ammar
文章链接: http://lizhaoloveit.cn/2016/04/23/Swift-Learning-%E4%B8%89/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Ammar's Blog
打赏
  • 微信
  • 支付宝

评论