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

So Finally Swift 5 is released, There are some new features and some featured are enhanced . to use the benefits of swift -5, we need to understand in details , Lets Begin

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.

Application Binary Interface (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.

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!”)

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):

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 })

Output = 3

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

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.

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

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.

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.

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).

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.

Using New Unicode Scalar Properties

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

let username = “mycodetips001”
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.

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: “Mycodetips”, zodiac: Leo)
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: “Mycodetips”, zodiac: Leo).

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.

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.