書名: Hands-On Design Patterns with Swift作者名: Florent Vilmart Giordano Scalzo Sergio De Simone本章字數: 120字更新時間: 2021-07-02 14:45:09
Range as Sequence
When using Range<Int> or ClosedRange<Int>, in addition to others, the Standard Library provides conditional conformance to the Sequence type, as follows:
extension Range: Sequence where Bound: Strideable, Bound.Stride : SignedInteger {
public typealias Element = Bound
public typealias Iterator = IndexingIterator<Range<Bound>>
}
Extract from Swift Core source code (https://github.com/apple/swift/blob/master/stdlib/public/core/Range.swift).
This means that you can use this range as the source for iterating on it, as shown in the following example:
let doubles = (1..<10).map { $0 * 2 } // [2,4,6,8,10,12,14,16,18]
for i in 1..<10 {
// do something with i
}
Because the Sequence conformance is provided as a conditional conformance, you can also define your own types that will allow for transforming Ranges to Sequences.
推薦閱讀
- 漫話大數據
- Mastering Ninject for Dependency Injection
- 正則表達式必知必會
- App+軟件+游戲+網站界面設計教程
- 數據結構與算法(C語言版)
- Mastering Machine Learning with R(Second Edition)
- Dependency Injection with AngularJS
- 計算機應用基礎教程上機指導與習題集(微課版)
- 編寫有效用例
- Google Cloud Platform for Developers
- Mastering LOB Development for Silverlight 5:A Case Study in Action
- 區域云計算和大數據產業發展:浙江樣板
- Visual FoxPro數據庫技術基礎
- Oracle 11g+ASP.NET數據庫系統開發案例教程
- 數據庫查詢優化器的藝術:原理解析與SQL性能優化