Swift 5 features With Examples

Swift 5 has released and is available with Xcode 10.2. Today we’ll be discussing what it brings to the table.

Swift 5 Features

1. ABI Stability

Swift 5 is ABI Stable!

What is ABI Stability?
ABI stands for Application Binary Interface.
It enables binary compatibility between apps and libraries compiled with different Swift versions.
So far every iOS application ships its own Swift version. This is because Swift isn’t available as a part of the iOS itself.

From Swift 5, ABI stability would allow future swift versions to be binary compatible with Swift 5.

Hence we won’t have to ship Swift with our applications anymore. This will reduce the bundle size.
Also, there will be compatibility between applications and libraries that may have been compiled with different Swift versions.

Generally, when discussing language features we fire up the Playground in our Xcode. You can do the same!

2. Raw Strings Literals

Escaping backslashes and quotes can always get frustrating.
With the new Raw String Literals, padding the strings with a # treats the quotes as they are and pads the slash with another.

The following code explains what we mean:


let regularString = "\Hello \Swift 5"
let rawString = #"Hello Swift 5"#
let rawQuote = ###"We have no "limits"###
swift-5-raw-strings

 

Swift 5 Raw Strings

As you can see we don’t need to escape the quotes.

In order to make escaping work with the above syntax, we need to pad the backslash with a # as #(). It changes the syntax of string interpolation slightly as shown below:


let name = "Journaldev"
let greeting1 = #"Hello, #(name)!"#
let greeting2 = #"Hello, (name)!"#
swift-raw-string-backslash

 

Swift Raw String Backslash

The following statement can now be easily reduced using hashtag:


let regex1 = "\\[A-Z]+[A-Za-z]+\.[a-z]+"
let regex2 = #"\[A-Z]+[A-Za-z]+.[a-z]+"#

3. Integer Multiples

Before swift 5:


let myNumber = 4
if myNumber % 2 == 0 {
    print("number is multiple of 2")
}

Now we have the isMultiple(of:) method:


4.isMultiple(of: 2)
6.isMultiple(of: 3)

4. Flatten Optional try?

Earlier try? used to give us nested optional like String?? or Int??.
In Swift 5, try?.someExpr() behaves the same way as foo?.someExpr()


//Swift 4.2 : String??
//Swift 5 : String?
let messages = try? person?.getName()

5. Result Type

Result Type is a much-needed feature. It forces you to handle success and error parts of a response/result gracefully before accessing the actual value.


enum Result {
    case value(Wrapped)
    case error(Failure)
}

Example:


let result = Result { try String(contentsOfFile: "xyz") }
switch result {
case .success(let string):
    print(string)
case .failure(_):
print("failure")
}

The above snippet prints failure.

Result Type is useful in URL and async requests!

6. Handle Future Enum cases

Swift requires switch cases to be exhaustive.
One way to deal with this is by using a default case.
The default case handles all the cases for which you want to handle commonly.

Future Enum cases has a syntax @unknown default:
It is used only instead of default case.
Whenever a new enum is added, this case indicates you with warning, whether you want to handle that enum case separately.

7. Compact Dictionaries

Instead of using map, reduce and filter to filter out nil or odd values, Swift 5 provides with:
compactMapValues(_:)

It can be used as:


let students = ["Anupam": "10", "Chugh": "ten"]
let mapStudents = students.compactMapValues(Int.init)
print(mapStudents)
let dictionary = ["A" : 1, "B" : 2, "C": nil]
let output = dictionary.compactMapValues{$0}
print(output)

The output in the playground for each line is”

swift-5-compact-values

 

Swift 5 Compact Values

8. @dynamic callable

Swift extends its interoperability to other languages like Python, JS by using dynamic callables.

An example from the docs shows how to :


class Dog:
    def __init__(self, name):
        self.name = name
        self.tricks = []  # creates a new empty list for each `Dog`
    def add_trick(self, trick):
        self.tricks.append(trick)

Now to call these in Swift, we simply need to do:


//import DogModule.Dog as Dog
let Dog = Python.import.call(with: "DogModule.Dog")
// dog = Dog("Brianna")
let dog = Dog.call(with: "Brianna")
// dog.add_trick("Roll over")
dog.add_trick.call(with: "Roll over")

That’s a wrap on this tutorial on Swift 5 Features.

By admin

Leave a Reply

%d bloggers like this: