Swift 2: Can we count on you?


It's mentioned in the WWDC 2015: What's New in Swift video that methods are becoming the norm over generic functions. And one of the things that you'll notice when fixing your code is that rather than use count() or what used to be countElements() you will now be required to use simply a count property for arrays and strings.
let array = [1,2,3,4,5,6]
array.count // 6
Similarly if we wish to map(), the more generic way of doing things is no longer available and we are forced to call the array method map() instead.
let array = [1,2,3,4,5,6]
map(array){$0 + 1} // error: map() no longer available
array.map{$0 + 1} // [2, 3, 4, 5, 6, 7]
In addition, you can longer simply count a string, you must explicitly access the characters property of the string (which returns a CharacterView), which can then be counted.
let str = "Hello Swift!"
str.characters.count // 12
These changes have been made to make code clearer, but also to help in hinting as to the methods available to an instance.

Endorse on Coderwall

Comments