Swift 4.0 New updates !!!

Mohit Bhalla
4 min readAug 12, 2017

In this blog I am going to explain some new updates introduced in Swift 4.

Initials to start with Swift 4.0

Swift 4 is the latest major release from Apple scheduled to be out of beta in the fall of 2017 and swift-4.0-branch is available to download at https://swift.org/download/#snapshots.

Apple announced Swift 4 as part of Xcode 9. Xcode 9 simultaneously supports both Swift 4 as well as an intermediate version of Swift 3 in Swift 3.2. You can download the latest version of Xcode 9 from Apple’s developer portal (you must have an active developer account).

So lets start..

Smart KeyPaths: Key-Value Coding — SE-0161

Swift 4 Provides cool way to access property value. You can grab root object name and drill down upto any property name to get its value. Key path starts with \ operator.

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

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

print(employee[keyPath:\Employee.address.state])

It will print following output.

Delhi

Strings are collections again SE-0163

Apple have backtracked i.e. strings are collections again as it was in swift 1.x .Now we don’t need string.characters.xxx for string manipulation.

let str = "Mohit Bhalla"for ch in str {
print(ch)
}

Dictionary and Set enhancements — SE-0165

  1. Now we can create a dictionary using array elements.
var animals = ["Cat","Dog","Tiger","Elephant"]
let animalDictionary = Dictionary(uniqueKeysWithValues: zip(1…, animals))
print(animalDictionary)

Which will produce following output

["0":"Cat", "1":"Dog", "2":"Tiger", "3":"Elephant"]

2. Default value if no value for key is found.

print(animalDictionary[4, default: “No Animal with this identity exist”])

Which will produce following output.

No Animal with this identity exist

3. Partition array in different buckets

Here is the cool way to initialize a Dictionary from Sequence and to group them into buckets.

var animals = ["Cat","Dog","Donkey","Tiger","Elephant"]
let animalDictionary = Dictionary(grouping: animals, by: { $0.first! })
print(animalDictionary)

Which will produce following output.

["C": ["Cat"], "D": ["Dog", "Donkey"],"T": ["Tiger"],"E”: [“Elephant”]]

Swift Archival & Serialization — SE-0166

In Swift 3, To serialize and archive your custom types you have to do many overheads like For class types you'd need to subclass NSObject and implement the NSCoding protocol. Value types like struct and enum required a number of hacks like creating a sub object that could extend NSObject and NSCoding.

Swift 4 simplifies the whole JSON archival and serialization process you were used in Swift 3. Now you only have to make your custom types implement the Codable protocol – which combines both the Encodable and Decodable ones.

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

Let’s fill out some details

let address = Address(street: “Laxmi Nagar”, zip: “110051”, city: “New Delhi”, state: “Delhi”)let employee = Employee(empId:"007" name: “Mohit Bhalla”, address: address)

Encoding ( Coverting Model to JSON )

let encoder = JSONEncoder() 
do
{
let encoded = encoder.encode(employee)
if let json = String(data: encoded, encoding: .utf8) {
print(json)
}
}
catch let error
{
print("Error while encoding Model \(error)")
}

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

{"empId": "007", "name":"Mohit Bhalla","address":{"state":"Delhi",”street":"Laxmi Nagar","zip":"110051","city":"New Delhi"}}

Decoding ( Coverting JSON to Model )

do {
let decoded = JSONDecoder().decode(Employee.self, from: encoded) {
print(decoded.name)
print(decoded.address)
}
catch let error {
print("Error while decoding JSON \(error)")
}

It will print following output.

Mohit Bhalla
Address(street: “Laxmi Nagar”, zip: “110051”, city: “New Delhi”, state: “Delhi”)

Multi-Line String Literals — SE-0168

Till Swift 3 , For adding new lines we need \n and escaping double quotes in string which was not the pleasant task.

Swift 4 addressed this issue by introducing Multi-Line String Literals support.

Start string literal with (”””) => press return key => start writing strings (can include line breaks/double quotes)=> End string literal with (”””)

let multiLine_String = """one "1"two "2"three "3""""print(“\(multiLine_String)”)

Which will produce following output.

one "1"
two "2"
three "3"

One-sided Ranges — SE-0172

In Swift 4, Now we can use one side range to extract sub-collection from collection where missing side will automatically treated as start or end of sequence.

var animals = ["Cat","Dog","Tiger","Elephant"]let firstTwo = names[..<2]let lastThree = names[2…]print(firstTwo)
print(lastThree)

Which will produce following output.

["Cat", "Dog"] 
["Tiger", "Elephant"]

MutableCollection.swapAtSE-0173

In Swift 3.x, The swap(_:_:) mutating method was used that takes two elements of a certain array and swaps them on the spot:

var animals = ["Cat","Dog","Tiger","Elephant"]
swap(&alphabets[0], &alphabets[1])

Now in Swift 4, New swap function takes indices of elements which are to be swapped. swapAt(_:_:)

var animals = ["Cat","Dog","Tiger","Elephant"]
animals.swapAt(1,3)
print("\(animals)")

Which will produce following output.

["Cat,"Elephant", "Tiger, "Dog"]

Next

In iOS , Power usage and memory consumption are extremely important considerations for iOS apps, and there are many other considerations as well. If app is not tunned properly it will affect UX aspect of app. To make you app more responsive and efficient go through the link ( iOS Performance Tunning )for more info.

Happy coding and keep sharing :)

--

--

Mohit Bhalla

Principle Engineer iOS, Wynk, Airtel | ex Hindustan times