In this post, I would like to share what’s new in Swift 4.2. All the code displayed in this post is available at my GitHub repo my-learnings/Swift4.2.
Random Number Generation
- Swift 4.2 added random number generator API to standard library. You can use it on
Int
,Double
,Float
,CGFloat
andBool
. - It also provides a convenient API
randomElement
which returns a random element from a sequence - It also provides the APIs
shuffle
andshuffled
to shuffle a sequence
|
|
Dynamic Member Lookup
Swift 4.2 introduces a dot syntax to access custom subscripts; this is much cleaner than the earlier square bracket calls. The compiler evaluates the subscript call dynamically at runtime, but provides a cleaner syntax.
In order to use this feature, you have annotate your type with @dynamicMemberLookup
and implement the method subscript(dynamicMember:)
|
|
Enumeration Case Collections
Swift 4.2 has added enumeration case arrays allCases
to all enumerations so that you can loop through all the cases of an enumerator without having to define an array of your own with all the cases. Swift does this automatically for you through the protocol.
If you want to customize the cases that is returned by allCases
, you can implement the CaseIterator
yourself.
|
|
Sequence Enhancements
Swift 4.2 made some neat enhancements to the Sequence APIs, for example, last(where:)
, lastIndex(of:)
, lastIndes(where:)
. They also added a new method allSatisfy(:)
that checks whether all elements in a sequence satisfy a specific condition.
|
|
Conditional Conformance
Swift 4.2 provides default implementation for conditional conformance to Equatable
, Hashable
and Codable
in extensions. In Swift 4.1, you had to manually implement these protocols even though the conforming protocol provided the implementations.
|
|
Also, optionals, arrays, dictionaries and ranges are Hashable
when their elements are Hashable
.
Other improvements
- Swift 4.2 provides universal hash functions which enables us to implement custom hash functions for a class much easier, more correct and performant. The
Hashable
protocol defines a new methodhash(into:)
which repalceshasValue
of Swift 4.1
|
|
- Convenience method to remove elements of a collection that satisfy a condition
|
|
- And finally, Yes! Swift 4.2 adds
toggle
toBool
|
|
References
Conclusion
All in all, Swift 4.2 contains many improvements to existing features and adds a few nice new features which makes the language more delightful to work with. This concludes the major enhancements in Swift 4.2. There are a few more enhancements listed in Ray Wenderlich tutorial. If you would like to know more, you can find them at https://www.raywenderlich.com/5357-what-s-new-in-swift-4-2.
It will be really interesting to see how these enhancements will bring Swift closer to ABI stability.
comments powered by Disqus