Swift 4 In Brief
Each year, WWDC brings new and exciting things to iOSLand.
Swift 4, which should be with us in September of this year, contains some interesting updates, and, thankfully, compatibility with Swift 3 was a top priority.
Here are some of the most notable changes:
Yet again, we can bask in the glory of iteration, reversal, filtering, and all the fun things we lost in Swift 2.
Currently String serves as its own subsequence to avoid the performance hit of copying. This shared storage can cause a memory leak; internally, String has a pointer to the start of its memory buffer and a reference to an owner for ARC. A subsequence of aString was also a String, with a shared reference to this owner, increasing the reference count — the entire buffer would therefore remain if the original String went out of scope.
With Swift 4, slicing will return a Substring. When this Substring is converted to a String, a copy of the subsequence will be made.
Gotcha — Do not store Substring long term, as it will have the same memory leak as before.
Dictionary Has Gained mapValues And filter, Both Of Which Return A Dictionary
No more iterating over the returned values of map and filter to re-create a Dictionary!
Can Initialize Dictionary From A Sequence Of (key, value) Tuples
For example — myDictionary.lazy.filter returns a LazyFilterCollection which in Swift 3 could not be passed to Dictionary to recover Dictionary functionality. No longer!
Dictionary Duplicate Key Resolution
Initalising a Dictionary with duplicate keys does not have to cause an error; pass in a closure which will be called with the old and new value for duplicate keys to handle them.
Default Values For Subscript Access To Dictionary
So simple, and yet so useful — [“myKey”, default: 0]
The size of a Dictionary can be set with .reserveCapacity(_:). This will reduce expensive reallocation processes if the size of the Dictionary is known.
An extension can access private variables directly without resorting to fileprivate annotations.
Using prefixes/postfixes, the most common uses of ranges are clearer and more concise.
(i...) counts up from i indefinitely, (..<i) and (...i) from the startIndex of a collection up to and including i.
These can also be used in pattern matching -
case ...2 //match anything equal or less than 2
Composed using """triple quotes""" — can still use \(property) within them and, more excitingly, no need to escape quotes!
If there is ongoing mutation of a variable, like in a loop, this variable will not be mutable elsewhere.
Conform To A Protocol And Class
Saving the best for last — behold the joy!
let myArray: [UIView & MyProtocol])

