What’s new in Swift 4

Swift 4 stable release is just around the corner and swift-4.0-branch is available to download at https://swift.org/download/#snapshots. In this writeup I will take you through some of the features which are added in Swift 4.

Installing swift-4.0 Snapshot Toolchain

  1. Please head over to https://swift.org/download/#snapshots and get Xcode from download section.

2. After installing toolchain navigate to Xcode -> Toolchain and select Swift 4.0 Snapshot. I would recommend to restart xcode after selecting the toolchain.

Multi-Line String Literals — SE-0168

Adding new lines using \n and escaping double quotes in string is not always pleasant task.

Swift 4 has addressed this issue by giving Multi line string literal support.To begin string literal add three double quotes marks (”””) and press return key, After pressing return key start writing strings with any variables , line breaks and double quotes just like you would write in notepad or any text editor. To end multi line string literal again write (”””) in new line.

let multiLineStringLiteral = """
This is one of the best feature add in Swift 4
It let’s you write “Double Quotes” without any escaping
and new lines without need of “\n”
"""
print(multiLineStringLiteral)

Which produces following output.

“This is one of the best feature add in Swift 4\nIt let’s you write “Double Quotes” without any escaping\nand new lines without need of “\n””

String will be treated as collection — SE-0163

Just like it was in Swift version 1.x Strings can be treated as collection. You no longer need to write string.characters.xxx to perform string manipulation.

let message = "Message!"
message.count // no need of message.characters.count
for character in message {  // no need of message.characters
print(character)
}

Which will produce following output.

8
M
e
s
s
a
g
e
!

MutableCollection.swapAt — SE-0173

Although this is very small change but must needed to be compliant with part of the introduction of the Law of Exclusivity.

New swap function now takes indices of elements which are to be swapped.

var names = [“Vipul”,”Vinay”,”Vishal”,”Akshay”]
names.swapAt(2,3)

Which will produce following output.

[“Vipul”, “Vinay”, “Akshay”, “Vishal”]

One-sided Ranges— SE-0172

Seems swift got inspired from Python to bring in this awesome feature. Now we can use one side range where missing side will automatically treated as start or end of sequence.

let names = [“Vipul”, “Vishal”, “Vinay”, “Vikas”, “Vineet”]
let firstTwoString = names[..<2]
let lastThreeString = names[2…]
print(firstTwoString)
print(lastThreeString)

Which will produce following output.

["Vipul", "Vishal"] // [..<2] => [0,1]
["Vinay", "Vikas", "Vineet"] // names[2…] => [2,3,4]

Dictionary and Set enhancements— SE-0165

  1. Now you can create a dictionary using array elements.
let friends = [“Vipul”, “Vinay”, “Vishal”]
let friendsDictionary = Dictionary(uniqueKeysWithValues: zip(1…, friends))
print(friendsDictionary)

Which will produce following output.

[2: “Vinay”, 3: “Vishal”, 1: “Vipul”]

2. Provide default value if value for key does not exist. In following statement. in following statement if there is no value for key 10 found then it will print default value.

print(friendsDictionary[10, default: “No Friends Exist yet!”])

Which will produce following output.

No Friends Exist yet!

3. Partition array in different buckets

let mates = [“Akshay”, “Anil”, “Vishal”, “Vinay”, “Ankit”]
let buckets = Dictionary(grouping: mates, by: { $0.first! })

If you carefully read above syntax, What I am trying to do over here is try to form different buckets where each bucket will contain mates having same first character in their name. Output will be as below.

[“A”: [“Akshay”, “Anil”, “Ankit”], “V”: [“Vishal”, “Vinay”]]

Swift Archival & Serialization — SE-0166

Good News! Swift 4 comes with built in encoders and decoders for JSON. JSON <-> Model conversion is comes built in ( Although you can customize that behavior if required ).

Define Models

struct Address:Codable {
var street:String
var zip:String
var city:String
var state:String
}
struct Person: Codable {
var name: String
var address: Address
}

Let’s fill out some details

let address = Address(street: “Apple Bay Street”, zip: “94608”, city: “Emeryville”, state: “California”)
let person = Person(name: “Steve Jobs”, address: address)

Encoding ( Model -> JSON )

let encoder = JSONEncoder() // Define JSONEncoder
if let encoded = try? encoder.encode(person) {
if let json = String(data: encoded, encoding: .utf8) {
print(json)
}
}

It will print following output. ( No more third party libs to convert model into JSON :) )

{“name”:”Steve Jobs”,”address”:{“state”:”California”,”street”:”Apple Bay Street”,”zip”:”94608",”city”:”Emeryville”}}

Decoding ( JSON -> Model )

let decoder = JSONDecoder()
if let decoded = try? decoder.decode(Person.self, from: encoded) {
print(decoded.name)
print(decoded.address)
}

It will print following output.

Steve Jobs
Address(street: “Apple Bay Street”, zip: “94608”, city: “Emeryville”, state: “California”)

Smart KeyPaths: Key-Value Coding — SE-0161

This is one of my favorite feature in Swift 4. You can grab root object name and drill down upto any property name to get its value. Key path starts with \ operator. Let’s see it in action.

Define models

struct Address {
var street:String
var zip:String
var city:String
var state:String
}
struct Friend {
var name: String
var addresses: [Address]

var primaryAddress: Address {
return addresses.first!
}
}

Let’s fill out some details

let address1 = Address(street: “Apple Bay Street”, zip: “94608”, city: “Emeryville”, state: “California”)
let address2 = Address(street: “27th Way”, zip: “85042”, city: “Phoenix”, state: “Arizona”)
let friend = Friend(name: “Steve Jobs”, addresses: [address1,address2])

Now If we have friend object and want to get to California value then following key path syntax should be used.

print(friend[keyPath:\Friend.primaryAddress.state])

It will print following output.

California

Much more to come……

First stable version of Swift 4 is expected to start rolling out in June, so we might see many more proposals to make their way in Swift 4.

Happy Coding :)