天天看點

Swift中的奇淫巧技

目錄 stride ,

self

, typealias , zip

###1>巧用 stride 循環

stride 是 Strideable 協定中定義的一個方法, 它可以按照指定的遞進值生成一個序列。可以用在 Swift 的循環文法結構中。定義如下:

public func stride(to end:Self, by stride:Self.Stride) ->StrideTo<Self>
public func stride(through end:Self, by stride:Self.Stride) ->StrideThrough<Self>

複制代碼
           

這兩個方法的差別很簡單:(是否包含終點值)

for i in 0.stride(to:5, by:1) {
	print(i)//0,1,2,3,4
}
for i in 0.stride(through:5, by:1) {
	print(i)//0,1,2,3,4,5
}

複制代碼
           

那在循環中可以怎麼用呢:

//(by:可以傳入循環的步長)
for i in 0.stride(through: 10, by: 3) {
    print(i) //0,3,6,9
}
複制代碼
           

這個寫法類似于 python 中的 for 循環寫法

for i in range(0,10,3):##(起始值,終止值, 步長)
    print(i) ##0,3,6,9
複制代碼
           

###2>神奇的

self

問題來源 這兩天微網誌上也有讨論詳見

###如果你的變量如果和 Swift 的關鍵字沖突的話,你可以使用' '包裹住變量名,這樣就可以用了

self.saveButton.action { [weak self] _ in
     guard let `self` = self else { return }
     //do something
 }

複制代碼
           

###3>typealias的一點小用法 之前寫過一篇來介紹 typealias的用法點選檢視

現在在項目中有一點小更新,讓typealias更加好用,用 private 來定義 typealias, 實作代理方法的分離,讓項目結構更加清晰

private typealias Delegate = ViewController
extension Delegate: UITableViewDelegate {
	//delegate method
}

private typealias DataSource = ViewController
extension DataSource: UITableViewDataSource {
	//dataSource method
}

複制代碼
           

###4>zip函數的一點小小用法 首先看看 zip 函數是怎麼定義的

public func zip<Sequence1 : SequenceType, Sequence2 : SequenceType>(sequence1: Sequence1, _ sequence2: Sequence2) -> Zip2Sequence<Sequence1, Sequence2>
複制代碼
           

可以看到zip()函數接收兩個序列,并且傳回一個Zip2Sequence類型的資料 但什麼是 zip2Sequence呢?還是來個小例子來說明吧

let a = [1,2,3]
let b = ["one", "two", "three"]
let c = zip(a, b)
複制代碼
           

那麼 c的值什麼呢?

**▿ Swift.Zip2Sequence<Swift.Array<Swift.Int>, Swift.Array<Swift.String>>**
**  ▿ _sequence1: 3 elements**
**    - [0]: 1**
**    - [1]: 2**
**    - [2]: 3**
**  ▿ _sequence2: 3 elements**
**    - [0]: one**
**    - [1]: two**
**    - [2]: three**
複制代碼
           

這樣我們就可以拼一個 dictionary

var dic: [String: Int] = [:]
for (i, j) in ccc {
    dic[j] = i
}
**["one": 1, "three": 3, "two": 2]**
複制代碼
           

現在跳出 swift, 來看看 python 中的 zip 函數

x=['one','two','three']
y=[80,90,95]
d=dict(zip(x,y))
**[('bob', 80), ('tom', 90), ('kitty', 95)]
複制代碼
           

python 中的 zip 比 swift 簡便不少