What’s new in latest Swift 5.0- Features & Updates

What's new in latest Swift 5.0- Features & Updates

Great news! In the new update of Xcode 10.2, Swift 5 is now available which brings ABI stability at long last. Not only this, other various key features have also implemented, including Future Enum Cases, Dynamic Callable Types, checking for Integer Multiples, Raw String, a RESULT type and many more.

With the Swift 5, it has added many latest and exciting features to Swift 4.2, and made the language ABI stable. In the Swift language evolution, this will act as an important milestone by reducing the need of changes in the near future.

What is ABI stability – Application Binary Interface, connect swift binaries with different libraries and components when app runs. It characterize low level details such as how data is represented in memory, where metadata is located, how to access it and how called a function. Till Swift 4.2 apps were not ABI stable, then each binary and bundles has its own version of the Swift Dynamic Library. It persisted in the each app instead of iOS operating system.

Today with ABI stability binary compatibility between apps and libraries compiled with every version of Swift, thereby the Swift standard library and runtime get embedded in the iOS, so apps don’t distribute their own copy of the libraries on any platform. For instance, App 1 is utilizing Swift 5.0, yet App 2 is utilizing Swift 5.2, and they both consuming Swift ABI installed iOS.

The reason why ABI stability has proven such a revolution –

  1. Bundle size will diminished
  2. Language changes will be little and less regular
  3. Developers can make Pre-compiled frameworks in Swift because no need to embed the swift. In Swift 4.2, frameworks are compiled when compiling an app.
  4. Less Migration

Result type – This is the feature which many of us have been waiting for. The Result type forces the programmer to explicitly handle the failure and success cases before they can gain access to the actual value.

Enum Result {
   Case value (Wrapped)
   Case error (Failure)

Swift 4.2 currently lacks the ability to express this impossibility. Now in Swift 5 using RESULT for the same condition allow us to write more elegant code :

URLSession.shared.datatask(with URL){ result: Result < (response: URLResponse, data: Data),
switch result {
   Case let .success(success):
      handleResponse(success: response, detail: .success.data)
   Case let .error (error):

we can write more clean & readable code which enables constraining the exact error type that may be returned.

Computing & Unwrapping Dictionary Values – In Swift 5, much needed improvements to dictionaries are finally conducted which is a new method “compactMapValue” for dictionaries. It is bringing together the “compactMap()” functionality from array with the “mapValues()” method from dictionaries. compactMapValue method can also be used to unwrap optionals and discard nil values without performing any sort of transaction.

For example, here’s a dictionary of students in a class, along with there valid grades. One student did not get grades who marked as nil.

let students = [“Harry”: “65”, “Ron”: “52”, “Hermione”: “86”, “Luna”: nil]

We can create a new dictionary with name and grades as an integer, with one nil graded student removed with compactMapValues :

let mapstudentValues = students.compactMapValues{Int($0)}

Alternatively, we could just pass the Int initializer directly to compactMapValues(), like this

let mapstudentValues = students.compactMapValues(Int.init)

It achieves the something in much fewer lines of code, flawless!

Swift 5 also renames “dictionaryLiteral” to “keyValuePairs”

let pets: keyValuePairs = [“dog”: “Barks”, “snake”: “Hiss”]

Count sequence – Swift 5 presents another new “count(where:)” method that execute the equivalent of a filter() and count in a single parse. This spares the creation of a new array that immediately gets disposed of and gives an unmistakable & brief answer of a typical issue. It is available to all the types that observe to “Sequence”, so we can use it on sets and dictionaries. In this example, creates an array of test results, and count how many are greater or equal to 42.

let marks = [95,80,42,38,34]
let passCount = marks.Count {$0 >= 42}

And this counts how many names in an array starts with John.

let names = [“John Abraham”, “Michael Jackson”, John applease”, “Larry Trison”
let johnCount = names.Count {$0.hasPrefix(“Jhon”)}

This element was pulled back in beta testing since it was causing execution issues for the type checker. Ideally it will return in time for Swift 5.1, maybe with another name to keep away from issues.

Integer Multiple – In Swift 4.2 we regulate whether a number is a multiple of another with remainder operator “if number % 2 == 0” which was less clear. Now in Swift 5 “isMultiple(of:) method is adds in integers for the above condition.

let number = 6
If number.isMultiple(of: 2) {

Raw String Escaping – Swift 5 introduce raw string. We can add # at the beginning and end of the string so we can use backslashes and quote marks without issue. While in swift 4.2 we use escape sequences to represent backslashes & quote marks in string.

let raw = #”We can create “raw”\”plain”string in Swift 5.”#
let multipleString = #””” The man who acts,
                   Who sings,
                   Who dances is #(answer).

In swift 4.2 writting a simple regex to find a key paths
let regex = “\\[A-Z]+[A-Za-z]+\.[a-z]+”

In Swift 5

let regex = # “\[A-Z]+[A-Za-z]+.[a-z]+”#

Dynamically Callable Types – A new @dynamicCallable attribute is added in Swift 5, which comes up with the ability to mark a type as being directly callable. @dynamicCallable is the normal extension of @dynamicMemberLookup and serves the same needs: to make it simpler for Swift code to work alongside dynamic scripting languages, for example Ruby, Python and Javascript.

func dynamicallyCall(withArguments args: [Int]) -> Int
func dynamicallyCall(withKeywordArguments args: KeyValuePairs) -> Int

The first of those is utilized when you call the type without parameter names (for example a(b, c)), and the second is utilized when you do provide names(for example a(b: John, c: Sandy)).

@dynamicCallable is extremely adaptable about which data types its methods accept and return, enabling us to benefit from all of Swift’s type safety while still having some wriggle room for advanced usage.

There are some essential guidelines to know about when utilizing @dynamicCallable:
– You can apply it to the structs, enums, classes, and protocols.
– If we execute withKeywordArguments: and don’t execute withArguments:, our type can still be called without parameter names – we’ll simply get empty strings for the keys.
– If our executions of withKeywordArguments: or withArguments: are marked as throwing, calling the type will likewise be throwing.
– We can’t add @dynamicCallable to an extension, just the essential definition of a type.
– We can even now add other methods and properties to our types, and use them as normal.
– Maybe more imperatively, there is no support for method resolution, which implies we should call the type directly (for example random(numberOfZeroes: 5)) instead of calling specific methods on the type (e.g. random.generate(numberOfZeroes: 5)).

Handling Future Enumeration Cases – In Swift 5 we can handle undefined enumeration case properly. It helps to distinguish between enums that are fixed and enums that might change in the future.With the @unknown attribute we would now be able to recognize two subtly different situations: “this default case should be run for all other cases because I don’t want to handle them individually,” and “I need to deal with all cases individually, but if anything comes up later on use this instead of causing a error.”

func errorEnum(error: PasswordError) {
   switch error {
   case .short:
     print(“Your password is too short.”)
   case .obvious:
     print(“Your password is too obvious.”)
   @unknown default:
     print(“Your password is not suitable.”)

There are numerous different upgrades which are not referenced in the article, for example, string — language level support, standard library enhancements and so on.

Never Miss Another Update
Subscribe to receive the latest updates

I have read and accept the Privacy Policy

We'd love to hear from you

I have read and accept the Privacy Policy
× Talk to us on WhatsApp!