Swift 5 is the first evolution language for all the Apple developers. In this blog, we shall cover what all features are introduced in the Swift 5.0 version. Many of these updates have a significant effect on the overall coding experience and help in increasing the efficiency of developers. So, let us have a look at the new Swift 5 features.
A most crucial section, API stability is one of the features updated. This shall enable the application to be integrated with libraries of different Swift versions while also allowing it for binary compilation.
In Swift 5, a new function, multiple(of:) is introduced for checking whether the specific integer is a multiple of another specified number or not.
Swift 5 also added raw strings in its language. Developers can now add a # at the beginning and end of any string to use backslashes and quote marks without any hurdles. Now, raw strings don't require escape of backslashes, so, in the regex, we can easily use half of the backslashes.
let backSlashString = #"" Without Backslash""#
let multilineInterpolation = #"""
Multiline string with
\#(backSlashString)
"""#
For useful mapping and filtering of dictionary values, Swift 5 introduced a new function called compactMapValues(_:)
Here:
let data = ["x": "1", "y": "three", "z": "///4///"]
let resultValues: [String: Int] = data.compactMapValues { str in Int(str)
Swift 5 has included an entirely new type called Result. The Result type has two cases,
Here's an example:
public enum Result
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"
}
}
Swift 5 has added a new @unkown keyword to the default switch case. This @unknown keyword acts as a trigger warning if non-exhaustive switch statements are being used.
Syntax:
switch CLLocationManager.authorizationStatus() {
case .authorizedWhenInUse, .authorizedAlways, .denied, .restricted:
break
@unknown default:
break
}
In Swift 5, the flattens 'try?' gives us similar behavior compared to 'as?' and another optional chaining. This eliminates the need for a separate nested optional code:
Here's an example:
struct NewUser {
var id: Int?
init?(id: Int) throws {
if id < 2 {
return nil
}
self.id = id1
}
}
var newUserId = try? NewUser(id1: 1)?.id // Swift 4.2 newUserId?? : Swift 5 newUserId?
In this blog, we have learned about Swift 5 new features, essential updates in the Swift standard libraries and other essential elements that shall help iOS and Swift Developers to get a hold on the Swift 5 language.