Swift

Swift 4.2 - What's New

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 and Bool.
  • It also provides a convenient API randomElement which returns a random element from a sequence
  • It also provides the APIs shuffle and shuffled to shuffle a sequence
1
2
let randomInt = Int.random(in: 0..<10)
let randomElement = ["one", "two", "three", "four"].randomElement()

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.

TDD in Xcode Playground

I use Xcode playground a lot in order to write code snippets - either to try out something that I read in a blog, or to demonstrate a code improvement that I want to suggest in a code review, or sometimes even to prototype a design before doing the full-blown implementation in Xcode project. During this experimentation phase, the correctness of the code was verified by analyzing the ouput displayed on the right-hand side column of the playground. This was really cumbersome and error-prone and I was hoping that there would be a better solution for this.