Swift 4 Features: Learn What Has Been Changed, With Examples

swift 4 features

Who should read this content:

  • Startups & Businesses – Who’re developing an iPhone app to expand their businesses.
  • iPhone App Developers – Who wants to learn all about swift 4 changes and new Swift features to improve the code of their current iPhone app projects.

Swift 4 is finally here, and it has brought some nice new additions and changes. Apple, in the major new release of everyone’s favorite iOS app development language, has introduced a variety of new Swift features and additions that will allow iOS app developers to write simpler and more safer code.

In fact, you’ll be happy to know that in the new Swift 4, there is nothing as dramatic as the epic changed announced with Swift 3 features, and the most changes in Swift 4 are indeed fully backward-compatible with your existing Swift code. So for the developers, Swift app development has not changed dramatically.

Now, without any further ado, let’s take a look at new Swift 4 features!

1) Archival & Serialization With JSON Encoding and Decoding

JSON parsing is one of the most discussed topics in the Swift community. And it’s good to know that they finally simplified the whole JSON archival and serialization process and pushed the idea to refresh the archival & serialization APIs in the Foundation framework.

In Swift 4, you no longer need to parse or encode your class, struct, or enum manually.

The new Encodable and Decodable protocols have been added in the new version of Swift, and you can make your classes confirm to them by simply adding Codable, an alias for Encodable & Decodable, to the class’s inheritance list.

After that, you can use the JSONEncoder to encode an instance of the class.

let wwdc = Conference(name: "Apple", city: "California", date: Date(timeIntervalSince1970: 0))
let jsonEncoder = JSONEncoder()
let jsonEncoded = try jsonEncoder.encode(wwdc)
let jsonString = String(data: jsonEncoded, encoding: .utf8) // {"name":"Apple","city":"California","date":-978307200}

This way, you can instantiate a JSONEncoder object to convert the struct to a JSON string representation.

The process to reverse a string works just as similarly, with new JSONDecoder class.

let jsonDecoder = JSONDecoder()
let decodedWWDC = try jsonDecoder.decode(Conference.self, from: jsonEncoded) // `decodedWWDC` is already of type Conference!

This way, you can pass the type of object to the Decode method, and let the decoder know what object to expect back from JSON data.

Although this is not the real power of the new API. in the new version of Swift, developers, instead of using a JSONEncoder, can use the new PropertyListEncoder and ProperlyListDecoder to store data in a plist file. Furthermore, it’s also possible to create a custom encoder and decoder. To achieve this, you only need to confirm your decoder to Decoder protocol and encoder to Encoder protocol.

2) Smarter Key Paths for Key-Value Coding

Key paths were added in Swift 3 to make it easier for iOS developers to reference properties in an object.

In simple words, instead of referencing an object key with a simple string literal, developers can use Key paths to enforce a compile-time check that a type contains the required key, for eliminating the common runtime error.

These key paths were indeed a nice addition in the Swift 3, but their use was limited to NSObject, and it also didn’t work well with structs. These were the main reason why key paths were given an API refresh in the new version of Swift 4.

To overcome the limitations, a new syntax was agreed by the community to specify a key path. Here’s how it looks in the new Swift 4:

struct Conference {
var name = ""
let city: String

let nameKeyPath = \Conference.name
let wwdc = Conference(name: "Apple", city: "California")
wwdc[keyPath: nameKeyPath] // "WWDC"

With NameKeyPath object, developers can describe a reference to the name property. In addition, it can also be used as a subscript on that object. Lastly, if you change the variable from Let to Var of WWDC, then you can also change a specific property through the key path subscript syntax.

3) Mixing Classes With Protocols

Swift 3 gave us the ability to combine protocols together when creating variables and constants, but the new version of Swift 4 goes one step further. It allows adding classes to the mix by using the same syntax.

Remember the time when you needed an object which both subclasses a class and confirmed to a protocol? Unfortunately, Swift 3 had no way to express this idea and required varied workarounds.

The new Swift 4, however, can express this idea now by using the ‘&’ symbol. It can be used to combine multiple protocols into a single type, and it now can also be used to combine protocols with a class.

let object: UITableViewController & KittenProvider

Now, remember that only one class can be added in any such type, as you can’t subclass more than one class at a time.

4) One-Sided Ranges

This is one of the nice and small Swift changes that are mostly self-explanatory. In the new version of Swift, ranges can now be one-sided. Swift 4 has received prefix and postfix versions of the half-open range and closed range operators for creating one-sided ranges.

For example, if you want to split an array into halves:

let middle = array.count / 2
let firstHalf = array[..<middle]
let secondHalf = array[middle...]

And, if you want to get a substring for a particular index:

let index = string.index(of: "e")!

In addition, you can also use it in Switch statements just like below:

switch x {
case ..<0:
case 0:
case 1..<10:
case 10..<100:
case 100...:

For one-sided range up to a given value, you can use ..<

And for the one-sided range starting at a given value, only … is allowed, as the distinction between … and ..< doesn’t make any sense.

5) Swap Vs SwapAt

In the older version of Swift, the Swap(_:_:), the mutating method used to take two elements of a certain array and swap them right away.

var numbers = [1, 5, 2, 8, 4, 10]
swap(&numbers[0], &numbers[1])

This solution was quite useful, but it still possessed one major drawback. The swapped elements were used to pass to a function as inout parameters so that it can access them directly.

The Swift 4 has a completely new approach with mutating method – swapAt(_:_:). This method takes two elements corresponding indices and swaps them just as before:

numbers.swapAt(0, 1)

6) Improved Dictionaries & Sets

The Dictionary and Set also received a new refresh in the Swift 4. They’re now much more pleasant to use, due to few utility methods being added.


The Dictionary now has mapValues method for changing all values, and avoiding the use of generic map method which needs working with the key, value tuples.

let conferences = ["WWDC": "Excellent", "AltConf": "Amazing", "Good": "Okay"]
// Map over all values in the dictionary.
let newConferences = conferences.mapValues { value in
return value + " Yes"

Filter Return Type

The Filter method in Swift 4 now returns an object of the same type you’re filtering with:

// The type of this variable is [String: String]
let wwdc = conferences.filter { $0.key == "WWDC" }

Defaults for Dictionary Lookup

Now in the new version of Swift, you can provide a default value when using the subscript syntax to make sure you don’t have to later unwrap an optional.

// Default value if key is not found.
let talkShow = conferences["True", default: "Not Found"]

Wrapping Up

Swift 4 might not have brought the dramatic changes we’ve seen earlier, but it’s still a solid improvement. And by the end of this blog, you might already be planning to start using them and make your code part clean and fresh. Therefore, we recommend that you start writing your new code in Swift 4 to take advantage of these useful new features. And if you get stuck somewhere or want to hire Swift developer, just fill out the below form with your requirements, and we’d be happy to assist you in your project.