Mallow's Blog

What’s New in Swift 5

Swift 5 is the major evolution for all Apple developers. In Swift 5, they have introduced many standard library and compiler updates. In this blog we will cover some of the important proposals accepted in Swift Evolution.

ABI Stability

One of the most important part of Swift 5 is the ABI stability. It enables binary compatibility to our application and library compiled with different version of Swift.

Function isMultiple(of:)

Swift 5 implemented a new function isMultiple(of:) for integers, to check if a given number is a multiple of another number.

let isMultipleOfTwo = 4.isMultiple(of: 2)


Raw String

Swift 5 also adds raw strings. We can add # at the beginning and end of the string, so we can use backslashes and quote marks without any issue. Since we don’t need to escape backslashes in raw strings, in regex we can use only half the number of backslashes.

let backSlashString = #"" Without Backslash""#
let multilineInterpolation = #"""
Multiline string with
\#(backSlashString)
"""#


Function compactMapValues()

Swift 5 introduced a new function for effectively mapping and filtering dictionary values called compactMapValues(_:)

let data = ["a": "1", "b": "three", "c": "///4///"]
let resultValues: [String: Int] = data.compactMapValues { str in Int(str) } // ["a": 1]


Result Type

Swift community added an entirely new type called Result in Swift. This type has two cases .success associated with any value and .failure associated with Error protocol.

public enum Result<Success, Failure: Error> {
    case success(Success), failure(Failure)
}

enum NetworkError: Error {
    case noResponse
    case noNetwork
}

struct User: Decodable {
    let id: Int
    let name: String

    enum CodingKeys: String, CodingKey {
        case id
        case name = "first_name"
    }
}

func getUser(from urlString: URL, completionHandler: @escaping (Result<User, NetworkError>) -> Void)  {
    Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: [:]).validate().responseJSON(completionHandler: { (response) in
        switch response.result {
        case .success:
            let jsonDecoder = JSONDecoder()
            let data = response.data
            do {
                let list: [User] = try jsonDecoder.decode([User].self, from: data)
                completionHandler(.success(list))
            } catch {
                completionHandler(.failure(NetworkError.noResponse))
            }
        case .failure(let error):
            completionHandler(.failure(NetworkError.noResponse))
        }
    })
}


Future Enum case

In Swift 5.0, a new @unknown keyword can be added to the default switch case. The @unknown keyword will trigger a warning, if we use non-exhaustive switch statement.

switch CLLocationManager.authorizationStatus() {
case .authorizedWhenInUse, .authorizedAlways, .denied, .restricted:
    break
@unknown default:
    break
}


Flatten Optionals

In Swift 5 flattens ‘try?’ gives us the same behaviour as ‘as?’ and optional chaining. Thereby it eliminates nested optionals.

struct NewUser {
    var id: Int?
    init?(id: Int) throws {
        if id < 1 {
            return nil
        }
        self.id = id
    }
}

var newUserId = try? NewUser(id: 1)?.id // Swift 4.2 newUserId?? : Swift 5 newUserId?


Conclusion

In this blog, we have learnt about important updates in Swift standard library, which will be helpful in developer productivity. You can view the entire list of updates here. Please check here to view recent proposals. It will be great to contribute in Swift Evolution which is open for all.

Srikanth Thangavel
iOS Team,
Mallow Technologies.

Leave a Reply

%d bloggers like this: