Apple gadgets are one of the most trusted and popular gadgets in the world. These gadgets use really cool iOS apps for functioning. Developing iOS apps with Swift programing language gives an edge to these apps. This is why we will be discussing the new version Swift 5 features in this blog.

We are a leading iOS app development company having an experience of developing 2000+ iOS apps for phones as well as iPads. We are writing this blog to try and help the developers as well as entrepreneurs to tell them about Swift 5 in detail. Herein we have covered 10 new and advanced features of Swift 5 programming language that can be the right choice for your macOS and iOS app development. So, let’s explore 15 language features of Swift 5 with in-detail information and examples.

From this article, you will discover:

  • What’s new in Swift 5? What are the new changes in Swift 5?
  • 15 new and advanced features of Swift 5
  • In detail explanation and examples of Swift 5 features

Introduction

A brand new version of the Swift programming language is here. Swift 5  was released in March 2019. Swift 5.0 brings a number of changes as well as some new features to make the development even simpler and better for swift app developers.

Today, we’ll have a look at some of the major changes and new features in Swift 5. We’ll also discuss how the process of making changes to the Swift language actually works, and why every iOS developer should know about it.

The Swift programming language was initially released in 2014 and was open-sourced at the end of 2015. As a result, more than 600 contributors have joined and are actively improving the language for seamless iOS app development.

After the Objective-C, Swift was originally the ‘second’ language for apps in the Apple ecosystem. But as Swift is open-source, it can be used on a number of other platforms, especially Linux.

This also led to the development of server-side Swift so that it can be used as a back-end language for web services. But why are we discussing all this? It’s important to realize that Swift is bigger than just building iOS apps.

So, without any further ado, let’s come straight to the topic and learn Swift programming features with an updated process.

What’s the Update Process of Swift Programming Language?

  • First, all the changes to the Swift programming language are proposed and discussed in a GitHub repository called Swift Evolution.
  • Anyone interested in the language can propose the changes, but they need to follow a process. You’ll find many proposed changes which are discussed first, in the Swift Forums, and then in communities.
  • After that, each proposed change is publicly reviewed by the Swift core team, which consists of Apple engineers like Ted Kremenek and Chris Lattner. You can find a list of current and past proposals in the proposals directory of  Swift Evolution.
  • A typical proposal usually includes source code and technical designs. If the proposal is accepted, the given source code is merged into the Swift source code.

Swift Evolution is more than just creating a good programming language. It also rejects proposals to ensure the integrity and robustness of the language. If you are interested, check out this SE – 0217, a rejected proposal about the bangbang operator !!

What’s New in Swift? New Features in Swift 5.0

1. ABI Stability

The major highlight of Swift 5.0 is ABI stability. ABI stability stands for Application Binary Interface stability, which is a binary equivalent of an API, an Application Programming Interface.

iOS app developers use various API of libraries to write code using Swift for your apps. For example, The UIKit framework provides API to interface with buttons, labels, and view controllers.

With ABI stability, when a user downloads and installs your app, they won’t have to download all the code your app requires. Most of those codes are already present on their iPhone, as part of iOS, its frameworks and libraries. Your app will just have to use the binary code already present. ABI stability in Swift 5 will make future apps smaller and easier to build.

2. Integer Multiples With “isMultiple(of:)”

There are a lot of use cases in practical programming when it comes to Swift. One of the most common is checking if a number is divisible by another number (Integer Multiples). As it again requires checking if a number is even or odd, the default approach is to use the remainder operator %.

Swift 5 comes with a new function isMultiple(of:) for checking if a given integer is a multiple of another number. This function of Swift 5 improves the readability of the code and also discoverable by the auto-completion of XCode.

Sample Usage:
let number = 42
if number.isMultiple(of: 2) {
    print("\(number) is even!")
}

3. The Result Type

Swift 5 introduces a new type called Result type for iOS app development. This type works with two states of a passed result: success and failure, and due to its high popularity, it’s now available in the Swift standard library.

Result type encapsulates possible return values and errors in one object. It leverages the power of enumerations and SWift 5 helps you write more meaningful code.

Sample Usage:
dataTask(with: url) { (result: Result) in
    switch result {
    case let .success(data):
        handleResponse(data: data)
    case let .error(error):
        handleError(error)
    }
}

4. Filter And Count With “count(where:)”

You might be already familiar with collection functions like map(_:), reduce(_:) and filter(_:). The problems with the above functions are — they make the code too verbose and wasteful. Though we only want to count, we first need to filter, and this is where ‘count(where:) comes in. This function allows us to filter and count in one function call seamlessly using Swift 5.

Sample Usage:
let scores = [1, 3, 8, 2, 5, 6, 2, 10]
let count = scores.count(where: { $0 > 5 })
print(count)
Output = 3

5. Flatten Nested Optionals With “try?”

Though it’s not wrong to use nested operators, they are confusing and seem unnecessary. Sometimes they need a larger number of operations for even doing a simple task. Swift 5 flatten the nested optional resulting from try? giving them the same behavior as? and optional chaining. This also helps the developer keep code neat and clean. 

Sample Usage:
if let engine = (try? bike?.getEngine()) as? Engine {
    // that's it
}

6. The New “compactMapValues()” Function For Dictionary

The standard Swift library comes with two important functions for arrays and a dictionary.

map(_:) – It applies a function to array items and returns the resulting array.

compactMap(_:) – it discards array items that are nil.

On the other hand, The mapValues(_:) function does the same for dictionaries except it doesn’t discard the nil array items. Swift 5 bring compactMapValues(_:) function for dictionaries.

It basically combines the compactMap(_:) function of arrays with the mapValues(_:) function of dictionaries for effective mapping and filtering values.

7. Standard Library Updates

Generics features for the standard library are the same for Swift 4.2 and Swift 5. Here, we’ll discuss the new features of Swift 5.

The standard library in Swift 5 includes many new features other than Swift 4.2 which help Swift programmers to manage their libraries well. Some of the major ones are as follows:

Improved Raw Text support for string literals.

SIMD and Result vector types are now available in the Swift 5 Standard Library.

String revamped with UTF-8 encoding for the performance boost.

Added more flexibility to construct text from data by enhancing String interpolation.

Performance improvements to Dictionary and Set

8. Package Manager Updates

Swift 5 brings a number of new features in Swift Package Manager. It includes target-specific build settings, customized deployment targets,  dependency mirroring, etc.

Furthermore, you can now import libraries in a REPL using the swift run command without any need to build an executable.

9. Additional Language and Compiler Updates

Another of the new features of Swift 5 is the language and Compiler Updates.

Swift 5 comes with Exclusivity Enforcement by defaults and allow exclusive access to memory for both debug and release builds. It now supports dynamic callable types and helps improve interoperability with languages like JavaScript, Python, and Ruby.

Swift also added Literal initialization via coercion, Identity key path, and other proposals as a result of the Swift Evolution process.

10. Migrating to Swift 5

Finally, if you are impressed by the Swift 5 features and looking for migration. There’s nothing to worry about. Swift 5 is compatible with Swift 4, Swift 4.1, and Swift 4.2 when it comes to efficient iOS app development.

You just need to use the Apple Xcode 10.2’s code migrator and many of the changes will be automatically handled by the code migrator itself. You can also use the migration guide available on the official website according to your expected result.

11. Raw Strings

Swift 5 allows you to create raw strings. The backlashes and quote marks are interpreted as the literal symbols instead of escapes characters or string terminators. The regular expressions and other user-cases become easier.

To use raw strings, you can put one or more # symbols before the strings:

let rain = #"The "rain" in "Spain" falls mainly on the Spaniards."#

The hashtag symbols at the start and end of the string are a part of the string delimiter. This way, Swift interprets that the standalone quote marks around “rain” and “Spain” should be treated as into quote marks rather than ending the string.

Similarly, raw strings allow you to use backslashes too:

let keypaths = #"Swift keypaths such as \Person.name hold uninvoked references to properties."#

Even here, the backslash is being treated as a literal character in the string, rather than an escape character.

An interesting feature of these raw strings is how you can use the hashtag at the start and end. Even if you want to use it more than once in an unlikely event. Consider this string: My cat said “meow”#goodcat. As there is no gap ahead of the hashtag, Swift will detect “# and understand it as the string terminator. In this situation we need to change our delimiter from #” to ##”, like this:

let str = ##"My cat said "meow"#goodcat"##

Make sure that the number of hashes at the end matches the number at the start, for the right result.

Raw strings and Swift’s multi-line string system are fully compatible with each other – all you need to do is use #””” to start, then “””# to end, like this:

let multiline = #"""
The answer to life,
the universe,
and everything is \#(answer).
"""#

12. Handling Future Enum cases

Switch cases need to exhaustive when it comes to Swift. This goes for Swift 5 as well. You can deal with this by using a default case. All the cases that you want to handle commonly are handled by the default case.

Future Enum cases have a syntax @unknown default: You can use it only instead of the default case.

If and when a new enum is added, you are indicated by the case with a warning if you want to handle that enum case individually.

13. Using New Unicode Scalar Properties

In Swift 4.2, you can implement text processing algorithms for unicode scalars like:

let username = "bond007"
var letters = 0
username.unicodeScalars.forEach {
  letters += (65...90) ~= $0.value || (97...122) ~= $0.value ? 1 : 0
}
print("Username has \(letters) letters.")

In this code, you calculate how many letters a username has by determining if each character’s unicode scalar constitutes a small letter or a capital letter.

The swift latest versions add properties to unicode scalars, that simplify text processing:

username.unicodeScalars.forEach { letters += $0.properties.isAlphabetic ? 1 : 0 }

In this code, isAlphabetic is being used to determine if every character is a digit. The linked proposal shows all the properties you can check.

14. String Interpolation

With Swift 5, the string interpolation has become more efficient and more flexible. They have created a whole range of new Swift features that were not there in Swift 4.2.

In simple words, this new Swift release has a revamped string interpolation system that lets you control how objects appear in strings as compared to Swift 4.2. Debugging is easier using Swift because it has default behavior for structs because it prints the struct name followed by all its properties. However, classes do not have this behavior. If you’re working with a class and want to format the output to make it user-facing, you can use the new string interpolation system.

For example, if we had a struct like this:

struct User {
    var name: String
    var zodiac: String
}

You can add a special string interpolation in order to print the results of the users neatly. For this, you can add an extension to String.StringInterpolation with a new appendInterpolation() method. Swift 5 has several of these built-in.

We are illustrating how to add an implementation that puts the user’s name and zodiac into a single string. It then calls one of the built-in appendInterpolation() methods to add that to our string, like this:

extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: User) {
        appendInterpolation("My name is \(value.name) and my Zodiac sign is \(value.zodiac)")
    }
}

Let’s now add a user and print out their data:

let user = User(name: "John Doe", zodiac: Cancer)
print("User details: \(user)")

That will print result as User details: My name is John Doe and my Zodiac is Cancer, whereas if we had used the custom string interpolation it would have printed User details: User(name: “John Doe”, zodiac: Cancer).

15. Dynamically Callable Types

Swift 5 package manager update supports dynamically callable types that help improve interoperability with dynamic languages such as Python, JavaScript, and Ruby.

Parentheses operator overload from C++ is similar to Dynamic calls, together with the keyword arguments from Python.

The major idea in Swift 5.0 is that you should be able to pass any arguments to it.

The tag names are not restricted to any method of header definition and can be called anything you prefer. You can do dynamic calls in two ways

1. With labels and

2. Without labels where the input order doesn’t matter for using this feature.

For instance, you create an object which a return JSON string. First, you define a struct and can mark it with at dynamiccallable. The version also synthesizes memberwise initializers for structs.

Now you create the first method without a label. Create a tag and parameter like below.

@dynamicCallable
struct createJson {
    func dynamicallyCall(withArguments args:[Int])->String {
        let jsonString = args.map{String($0)}.joined(separator: ",")
        return "(jsonString)"
    }
}

Make sure your parameter type is an array, however you can select the array type.