Swift World: New in Swift 3.1 - Concrete Constrained Extensions

315 阅读1分钟
原文链接: pengguo.xyz

Today, we’ll talk about concrete constrained extensions and Availability by Swift Version. Simply speaking, it helps extend concrete type with concrete constraint. In the change log of Swift, a simple definition is given as following.

extension Array where Element == Int { }

It extends Array with concrete type Int which means the extension will only works on Int. Let’s show a simple extension to get the sum of elements in the array.

extension Array where Element == Int {
    func sum() -> Int {
        return reduce(0, +)
    }
}

[1, 2, 4, 8].sum() // 15

In Swift 3.0, we can only use a protocol as constraint to extend concrete type. We will not give an example but you can find many example on Internet.

Thanks for your time.

Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>