swift 语法小记

文章目录
  1. 1. Swift 语法
    1. 1.1. Swift 中位移枚举如何表示
    2. 1.2. Counter loop
    3. 1.3. 编译符
    4. 1.4. String
    5. 1.5. GCD
      1. 1.5.1. once

Swift 语法

Swift 中位移枚举如何表示

OC 中位移枚举

1
2
3
4
5
6
7
// 位移枚举
typedef NS_OPTIONS(NSUInteger, Direction) {
Top = 1 << 0, // 0000 0001,
Bottom = 1 << 1, // 0000 0010,
Left = 1 << 2, // 0000 0100,
Right = 1 << 3, // 0000 1000,
}

Swift中位移枚举,替换方案是选项集合(OptionSet)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct Direction: OptionSet {
let rawValue: UInt
static let top = Direction(rawValue: 1 << 0)
static let bottom = Direction(rawValue: 1 << 1)
static let left = Direction(rawValue: 1 << 2)
static let right = Direction(rawValue: 1 << 3)
}

Swift就不再使用 &, | 运算了, 如果想使用多选,需要用数组代替,例如

```swift
let options: Direction = [.top, .bottom] // 与OC中 Top | Bottom 相同的作用
options.contains(.top)
options.contains(.left)

Counter loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
for i in 1...10 {

}

var g = (0..<10).generate()
while let i = g.next() {

}

// iterate over every other integer
for i in 0.stride(to: 10, by: 2) { print(i) }

// skip a specific number
for i in (0..<10).filter({ $0 != 5 }) { print(i) }

let a = ["one","two","three","four"]

// ok so this one’s a bit convoluted...
let everyOther = a.enumerate().filter { $0.0 % 2 == 0 }.map { $0.1 }.lazy

for s in everyOther {
print(s)
}

编译符

@discardableResult

1
2
3
4
5
6
7
8
9
10
11
func sum(a: Int, b: Int) -> Int {
return a + b
}
sum(a: 1, b: 2) // Result of call to 'sum(a:b:)' is unused

//表示取消不使用返回值的警告
@discardableResult
func sum(a: Int, b: Int) -> Int {
return a + b
}
sum(a: 1, b: 2) // No longer produce the warning

在 Objective-c中

1
- (NSString *)greeting __attribute__((warn_unused_result));

String

使用 String(describing: Class.self) 方法 代替 NSStringFromClass 得到 类的字符串

GCD

once