What are the new features in Swift 4.0?


In this tutorial, you are going to learn what changes have been released in Swift 4. Every time, Apple releases major versions with lots of improvements and additions to APIs.

The new features introduced in Swift 4.0 include improved key paths for key-value coding, encoding and decoding, multi-line string literals, Strings are collections, improved dictionary functionality, one-sided ranges, and many other code enhancements.

Encoding & Decoding

In Swift 4.0, Apple introduced the Codable protocol to make encoding and decoding easy for developers. You can implement serialization and deserialization in your code using this protocol. You can encode and decode your custom data types without writing much code.

You can store values in properties using encoding and can generate customized JSON from custom data types. Swift will automatically encode all properties inside your data type − you don't need to do anything.

Multi-line string literals

Before Swift 4.0, you were using \n inside strings to add new line breaks whenever you wanted. Evidently, using /n in strings doesn't look appropriate in code.

In Swift 4.0, Apple has addressed the problems with adding new lines and using double quotes in strings with a simplified multi−line string literal syntax. It allows you to add line breaks freely and to use three double quotes and the return key. Thereafter start writing strings with any variables, line breaks and double quotes as you want.

Example

let professional = "🧑💻"
let introduction = """Swift language is most popular among iOS developer \(professional).
   Further....
   Swift is a fantastic way to write software, whether it’s for phones, desktops, servers, or anything else that runs code.

   It’s a safe, fast, and interactive programming language.
   """
print(introduction)

Output

Swift language is most popular among iOS developer 🧑💻.

Further....

Swift is a fantastic way to write software, whether it’s for phones, desktops, servers, or anything else that runs code.

It’s a safe, fast, and interactive programming language.

Improved Key-Value Coding

A key feature of Objective−C is its ability to grab root object names and drill down any property names dynamically instead of specifying object keys with simple string literals. These references, key paths, enforce a compile-time check that a type contains the required key, thereby eliminating a common type of runtime error.

Dictionary Enhancements

Swift 4 added new robust functionality to Dictionary and Set. They are much more pleasant to use thanks to a few utility methods that have been added.

Swift 4 has a mapValues method on dictionaries to transform all values, and place them back into a dictionary using the original keys.

It’s now possible to access dictionaries and provide a default value when using the subscript syntax to avoid having to later unwrap an optional.

Finally, a new addition to Dictionary is a grouping initializer. This allows you to create a new dictionary by grouping the sequences of an existing collection by whatever criteria you set.

Enhanced Strings

In Swift 4, many improvements are made to Strings and new capabilities have been added to the Strings type. Let's see some of them.

Strings are once again collections

Strings are once again collections like they were before Swift 2.0. This change removes the need for a characters array on String. You can now iterate directly over a String object

Example

Here we are going to show how to iterate over a string's characters in Swift 4.0:

let stringValue = "Swift"
for char in stringValue {
   print(char)
}

Output

S
w
i
f
t

Before Swift 4, you used a String's characters array. But now you can iterate strings directly like other collections such as arrays.

StringProtocol

All the features of this protocol are implemented as strings. In Swift 4, Apple adds a new type called Substring to represent a subsequence of String. Strings and Substrings both conform to the StringProtocol and behave almost the same way.

Example

let sentence = "Swift language is great"
// How to make a subsequence?
let endIndex = sentence.index(sentence.startIndex, offsetBy: 4)
let languageName = sentence[sentence.startIndex...endIndex]

// print the substring and check the type of that string
print("Language name is: \(languageName) and it is type of: \(type(of: languageName))")

Output

Language name is: Swift and it is type of: Substring

Adaptation of Unicode 9

After Swift 4, strings are capable of interpreting Unicode characters correctly.

Example

print("👩💻".count) // Now: 1, Before: 2
print("👍🏽".count) // Now: 1, Before: 2
print("👨❤️💋👨".count) // Now: 1, Before: 4

Output

2
1
4

One-sided ranges

Swift adopted Python's one−side range where missing sides are automatically treated as start or end of sequence. We need not worry about potential breakage as it is not relevant to existing code.

Swift 4 added the ability to infer the start and end indices using one−sided ranges.

Example

let planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
let firstPart = planets[..<4] // Before: planets[planets.startIndex..<4]
let secondPart = planets[4...] // Before: planets[4..<planets.endIndex]
print("First part: \(firstPart)")
print("Second part: \(secondPart)")

Output

First part: ["Mercury", "Venus", "Earth", "Mars"]
Second part: ["Jupiter", "Saturn", "Uranus", "Neptune"]

Updates in Swift Package Manager

  • Swift package manager has undergone many changes. There are like:

  • Finding dependencies based on branch or commit hashes

  • Provide the location of each target's source files

  • Version control of acceptable packages

  • Defining the Swift version used for compilation

Generic Subscripts

Subscripts are an extremely valuable part of making data types accessible in an intuitive way. To improve their usefulness, subscripts can now be generic like the following:

Example

struct GenericDictionary<Key: Hashable, Value> {
   private var data: [Key: Value]
   init(data: [Key: Value]) {
      self.data = data
   }
   subscript<T>(key: Key) -> T? {
      return data[key] as? T
   }
}
// creating a dictionary of type: [String: Any]
var earthData = GenericDictionary(data: ["name": "Pathik Patel", "score": 80])

// name will automaitcally infers return type without "as? String"
let name: String? = earthData["name"]
print("Name is: \(name ?? "") and type: \(type(of: name))")

// score will automatically infers return type without "as? Int"
let score: Int? = earthData["score"]
print("Score is: \(score ?? 0) and type: \(type(of: score))")

Output

Name is: Pathik Patel and type: Optional<String>
Score is: 80 and type: Optional<Int>

Conclusion

The Swift language has really grown and matured over the years. These changes in Swift 4 give us a stable command of the Swift language. At first, dealing with the Swift code base was difficult due to the major changes that occurred, but now it is more stable.

Try to use most of the features in the code to write optimized code in the application.

Updated on: 05-Jan-2023

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements