Top 15 New Swift 5 Features to Consider in iOS App Development

Apple gadgets are one of the most trusted and popular gadgets in the world. These gadgets use really cool iOS apps for functioning. Developing iOS apps with Swift programing language gives an edge to these apps. This is why we will be discussing the new version Swift 5 features in this blog.

We are a leading iOS app development company having an experience of developing 2800+ iOS apps for phones as well as iPads. We are writing this blog to try and help the Swift iOS developer as well as entrepreneurs to tell them about Swift 5 in detail. Herein we have covered 10 new and advanced features of Swift 5 programming language that can be the right choice for your macOS and iOS app development. So, let’s explore 15 language features of Swift 5 with in-detail information and examples.

From this article, you will discover:

  • What’s new in Swift 5? What are the new changes in Swift 5?
  • 15 new and advanced features of Swift 5
  • In detail explanation and examples of Swift 5 features

Introduction

A brand new version of the Swift is here. However, if you are wondering about the Swift 4 vs Swift 5 difference, let us make it clear for you. Swift 5 improves Swift 4.2 by adding a slew of new features and stabilising the language’s ABI. This is a significant turning point in the evolution of the language, as there will be fewer changes in the future.

Today, we’ll have a look at some of the major changes and new features in Swift 5. We’ll also discuss how the process of making changes to the Swift language actually works, and why every iOS developer should know about it.

The Swift programming language was initially released in 2014 and was open-sourced at the end of 2015. As a result, more than 600 contributors have joined and are actively improving the language for seamless iOS app development.

After the Objective-C, Swift was originally the ‘second’ language for apps in the Apple ecosystem. But as Swift is open-source, it can be used on a number of other platforms, especially Linux.

This also led to the development of server-side Swift so that it can be used as a back-end language for web services. But why are we discussing all this? It’s important to realize that Swift is bigger than just building iOS apps.

Want to Develop an iOS App using Swift?

Looking to develop an iOS app? Get in touch with our experienced iOS app developers for a free consultation.

Cta Image

So, without any further ado, let’s come straight to the topic and learn Swift programming features with an updated process.

What’s the Update Process of Swift Programming Language?

  • First, all the changes to the Swift programming language are proposed and discussed in a GitHub repository called Swift Evolution.
  • Anyone interested in the language can propose the changes, but they need to follow a process. You’ll find many proposed changes which are discussed first, in the Swift Forums, and then in communities.
  • After that, each proposed change is publicly reviewed by the Swift core team, which consists of Apple engineers like Ted Kremenek and Chris Lattner. You can find a list of current and past proposals in the proposals directory of  Swift Evolution.
  • A typical proposal usually includes source code and technical designs. If the proposal is accepted, the given source code is merged into the Swift source code.
  • The Swift runtime update libraries which are built into macOS.

Swift Evolution is more than just creating a good programming language. It also rejects proposals to ensure the integrity and robustness of the language. If you are interested, check out this SE – 0217, a rejected proposal about the bangbang operator !! Now, let us discuss about what is Swift 5 and what are its features.

What’s New in Swift? New Features in Swift 5.0

Swift 5 is released and it is available in Xcode 10.2. We have discussed Swift 5 features, and how you can effectively use Swift for app development.

  1. ABI Stability

    ABI stability is one of the major highlights of Swift 5.0 features. ABI stability stands for Application Binary Interface stability, which is a binary equivalent of an API, an Application Programming Interface.

    iOS app developers use various API libraries to write code using Swift for your apps. For example, The UIKit framework provides API to interface with buttons, labels, and view controllers.

    With ABI stability, when a user downloads and installs your app, they won’t have to download all the code your app requires. Most of those codes are already present on their iPhone, as part of iOS, its frameworks, and API libraries. Your app will just have to use the binary code already present. ABI stability in Swift 5 will make future apps smaller and easier to build.

  2. Integer Multiples With “isMultiple(of:)”

    There are a lot of use cases in practical programming when it comes to Swift. One of the most common is checking if a number is divisible by another number (Integer Multiples). As it again requires checking if a number is even or odd, the default approach is to use the remainder operator %.

    Swift 5 comes with a new function isMultiple(of:) for checking if a given integer is a multiple of another number. This is one of the best Swift 5 features, that improves the readability of the code and also discoverable by the auto-completion of XCode.

    Sample Usage:
    let number = 42
    if number.isMultiple(of: 2) {
        print("\(number) is even!")
    }    
    
    Copy to Clipboard
  3. The Result Type

    Swift 5 introduces a new type called Result type for iOS app development. This type works with two states of a passed result: success and failure, and due to its high popularity, it’s now available in the Swift standard library.

    Result type encapsulates possible return values and errors in one object. It leverages the power of enumerations and SWift 5 helps you write more meaningful code.

    Sample Usage:

    dataTask(with: url) { (result: Result<Data, Error) in
        switch result {
        case let .success(data):
            handleResponse(data: data)
        case let .error(error):
            handleError(error)
        }
    }    
    
    Copy to Clipboard
  4. Filter And Count With “count(where:)”

    You might be already familiar with collection functions like map(_:), reduce(_:) and filter(_:). The problems with the above functions are — they make the code too verbose and wasteful. Though we only want to count, we first need to filter, and this is where ‘count(where:) comes in. This function allows us to filter and count in one function call seamlessly using Swift 5.

    Sample Usage:
    let scores = [1, 3, 8, 2, 5, 6, 2, 10]
    let count = scores.count(where: { $0 > 5 })
    print(count)
    
    Output = 3
    
    Copy to Clipboard
  5. Flatten Nested Optionals With “try?”

    Though it’s not wrong to use nested operators, they are confusing and seem unnecessary. Sometimes they need a larger number of operations for even doing a simple task. Swift 5 flatten the nested optional resulting from try? giving them the same behavior as? and optional chaining. This also helps the developer keep code neat and clean. 

    Sample Usage:
    if let engine = (try? bike?.getEngine()) as? Engine {
        // that's it
    }
    
    Copy to Clipboard
  6. The New “compactMapValues()” Function For Dictionary

    One of the swift 5 features includes “compactMapValues()” Function. The standard Swift library comes with two important functions for arrays and a dictionary.

    map(_:) – It applies a function to array items and returns the resulting array.

    compactMap(_:) – it discards array items that are nil.

    On the other hand, The mapValues(_:) function does the same for dictionaries except it doesn’t discard the nil array items. Swift 5 bring compactMapValues(_:) function for dictionaries.

    It basically combines the compactMap(_:) function of arrays with the mapValues(_:) function of dictionaries for effective mapping and filtering values.

  7. Standard Library Updates

    Generics features for the standard library are the same for Swift 4.2 and Swift 5. Here, we’ll discuss the new features of Swift 5.

    The standard library in Swift 5 includes many new features other than Swift 4.2 which help Swift programmers to manage their libraries well. Some of the major ones are as follows:

    • Improved Raw Text support for string literals.
    • SIMD and Result vector types are now available in the Swift 5 Standard Library.
    • String revamped with UTF-8 encoding for the performance boost.
    • Added more flexibility to construct text from data by enhancing String interpolation.
    • Performance improvements to Dictionary and Set
  8. Package Manager Updates

    This is one of the best Swift 5 new features, as this Swift Package manager includes target – specific build settings, customized deployment targets,  and dependency mirroring.

    Furthermore, you can now import libraries in a REPL using the swift run command without any need to build an executable.

  9. Additional Language and Compiler Updates

    Another of the new features of Swift 5 is the language and Compiler Updates.

    Swift 5 comes with Exclusivity Enforcement by defaults and allow exclusive access to memory for both debug and release builds. It now supports dynamic callable types and helps improve interoperability with languages like JavaScript, Python, and Ruby.

    Swift also added Literal initialization via coercion, Identity key path, and other proposals as a result of the Swift Evolution process.

  10. Migrating to Swift 5

    Finally, if you are impressed by the Swift 5 features and looking for migration. There’s nothing to worry about. Swift 5 is compatible with Swift 4, Swift 4.1, and Swift 4.2 when it comes to efficient iOS app development.

    You just need to use the Apple Xcode 10.2’s code migrator and many of the changes will be automatically handled by the code migrator itself. You can also use the migration guide available on the official website according to your expected result.

  11. Raw Strings

    This is one of the Swift 5 features that allows you to create raw strings. The backlashes and quote marks are interpreted as the literal symbols instead of escapes characters or string terminators. The regular expressions and other user-cases become easier.

    To use raw strings, you can put one or more # symbols before the strings:

    let rain = #"The "rain" in "Spain" falls mainly on the Spaniards."#
    
    Copy to Clipboard

    The hashtag symbols at the start and end of the string are a part of the string delimiter. This way, Swift interprets that the standalone quote marks around “rain” and “Spain” should be treated as into quote marks rather than ending the string.

    Similarly, raw strings allow you to use backslashes too:

    let keypaths = #"Swift keypaths such as \Person.name hold uninvoked references to properties."#   
    
    Copy to Clipboard

    Even here, the backslash is being treated as a literal character in the string, rather than an escape character.

    An interesting feature of these raw strings is how you can use the hashtag at the start and end. Even if you want to use it more than once in an unlikely event. Consider this string: My cat said “meow”#goodcat. As there is no gap ahead of the hashtag, Swift will detect “# and understand it as the string terminator. In this situation we need to change our delimiter from #” to ##”, like this:

    let str = ##"My cat said "meow"#goodcat"##
    
    Copy to Clipboard

    Make sure that the number of hashes at the end matches the number at the start, for the right result.

    Raw strings and Swift’s multi-line string system are fully compatible with each other – all you need to do is use #””” to start, then “””# to end, like this:

    let multiline = #"""
    The answer to life,
    the universe,
    and everything is \#(answer).
    """#
    
    Copy to Clipboard
  12. Handling Future Enum cases

    Switch cases need to exhaustive when it comes to Swift. This goes for Swift 5 as well. You can deal with this by using a default case. All the cases that you want to handle commonly are handled by the default case.

    Future Enum cases have a syntax @unknown default: You can use it only instead of the default case.

    If and when a new enum is added, you are indicated by the case with a warning if you want to handle that enum case individually.

  13. Using New Unicode Scalar Properties

    In Swift 4.2, you can implement text processing algorithms for unicode scalars like:

    let username = "bond007"
    var letters = 0
    username.unicodeScalars.forEach {
        letters += (65...90) ~= $0.value || (97...122) ~= $0.value ? 1 : 0
    }
    print("Username has \(letters) letters.")
    
    Copy to Clipboard

    In this code, you calculate how many letters a username has by determining if each character’s unicode scalar constitutes a small letter or a capital letter.

    The swift latest versions add properties to unicode scalars, that simplify text processing:

    username.unicodeScalars.forEach { letters += $0.properties.isAlphabetic ? 1 : 0 }
    
    Copy to Clipboard

    In this code, isAlphabetic is being used to determine if every character is a digit. The linked proposal shows all the properties you can check.

  14. String Interpolation

    With Swift 5 features, the string interpolation has become more efficient and more flexible. They have created a whole range of new Swift features that were not there in Swift 4.2.

    In simple words, this new Swift release has a revamped string interpolation system that lets you control how objects appear in strings as compared to Swift 4.2. Debugging is easier using Swift because it has default behavior for structs because it prints the struct name followed by all its properties. However, classes do not have this behavior. If you’re working with a class and want to format the output to make it user-facing, you can use the new string interpolation system.

    For example, if we had a struct like this:

    struct User {
        let name: String
        let zodiac: String
    }
    
    Copy to Clipboard

    You can add a special string interpolation in order to print the results of the users neatly. For this, you can add an extension to String.StringInterpolation with a new appendInterpolation() method. Swift 5 has several of these built-in.

    We are illustrating how to add an implementation that puts the user’s name and zodiac into a single string. It then calls one of the built-in appendInterpolation() methods to add that to our string, like this:

    extension User: CustomStringConvertible {
        var description: String {
            return "My name is \(name) and my Zodiac sign is \(zodiac)"
        }
    }  
    
    Copy to Clipboard

    Let’s now add a user and print out their data:

    let user = User(name: "John Doe", zodiac: "Cancer")
    print("User details: \(user)")
    
    Copy to Clipboard

    That will print result as User details: My name is John Doe and my Zodiac is Cancer, whereas if we had used the custom string interpolation it would have printed User details: User(name: “John Doe”, zodiac: Cancer).

  15. Dynamically Callable Types

    Swift 5 package manager update supports dynamically callable types that help improve interoperability with dynamic languages such as Python, JavaScript, and Ruby.

    Parentheses operator overload from C++ is similar to Dynamic calls, together with the keyword arguments from Python.

    The major idea in Swift 5.0 is that you should be able to pass any arguments to it.

    The tag names are not restricted to any method of header definition and can be called anything you prefer. You can do dynamic calls in two ways

    1. With labels and

    2. Without labels where the input order doesn’t matter for using this feature.

    For instance, you create an object which a return JSON string. First, you define a struct and can mark it with at dynamiccallable. The version also synthesizes memberwise initializers for structs.

    Now you create the first method without a label. Create a tag and parameter like below.

    @dynamicCallable
    struct CreateJson {
        func dynamicallyCall(withArguments args: [Int]) -> String {
            let jsonString = args.map { String($0) }.joined(separator: ",")
            return "[\(jsonString)]"
        }
    }    
    
    Copy to Clipboard

    Make sure your parameter type is an array, however you can select the array type.

Want to Develop an iOS App using Swift?

Looking to build an iOS app? Consult with our experienced iOS app developers for a successful and efficient app development experience.

Let’s see some of the frequently asked questions.

FAQs

When was Swift released?

Swift 1.0 was introduced in 2014, Apple’s WWDC. The language underwent an upgrade to version 1.2 during 2014. Later a major upgrade was announced as Swift 2 at WWDC 2015. At first, version 2.2 which was propriety language was made open-source software for Apple’s platforms and Linux on December 3, 2015, under the Apache License 2.0.

There have been many Swift releases and versions after that. Swift 5.0 was released in 2019.

What is the latest Swift version?

As of 2023, Swift 5.7 is the latest Swift version for Swift App Development. Swift 5.7 bring major additions to the language by improving developer experience by bringing improvement to the compiler. Even, though it includes tools in the Swift ecosystem including SourceKit-LSP, Swift Package Manager, and refined Windows support.

How do I migrate to Swift 5?

In order to migrate to Swift 5, you just need to use the Apple Xcode 10.2’s code migrator and many of the changes will be automatically handled by the code migrator itself. Invoke the Migrator manually from the menu Edit -> Convert -> To Current Swift Syntax…You can also use the migration guide available on the official website according to your expected result.

Which are the top apps made with Swift?

The following are the top apps developed with Swift.

  • Facebook
  • Uber
  • LinkedIn
  • WhatsApp
  • Airbnb

What can you do with Swift?

Being a fast and efficient app development language, Swift offers real-time feedback and is easily connected with Objective-C code. Therefore, you can save time by writing safer and more reliable code to develop an intuitive mobile app for your business.

What language are iOS apps written in?

iOS apps are written in 2 main languages which are Objective-C and Swift.

Which are the best Swift components?

Here is the list of Swift components for you to check.

  • iOS OTP Authenticator – This component helps to verify your mobile number with One Time Password (OTP).
  • Country Code Picker – Speed up building complex UIs and SwiftUI using the set of reusable components
  • iOS Intro Screens – Select country and enter the mobile number using the iOS-based CountryCode picker
  • iOS Custom Drawer Menu – Use the introduction screen in a scrollview manner at the time of app startup and manage dynamic views depending on the input images.

Conclusion

As Swift changes, it brings better Swift latest version features. Swift 5 comes with lightweight syntax and combines powerful type inference and pattern matching. The new version not only allows Swift developers to express complex ideas in a clear and concise manner but also improves the readability of the code during the iOS app development.

So, if you have any idea on iOS application development that you want to develop with Swift 5, share it with us. We are a leading Swift app development company based in India, Canada, and the USA and have experience of developing over 2500 iPhone apps that you can check and explore.

In case, if you have any query or confusion related to Swift programming questions like why select Swift as your programming language, iOS app development with Swift cost, how to hire an iPhone app developer, Swift source code examples, get in touch with us through our contact us form. One of our sales representatives will get back to you shortly. The consultation is free of cost.

Bhaval Patel

Written by

Bhaval Patel is a Director (Operations) at Space-O Technologies. He has 20+ years of experience helping startups and enterprises with custom software solutions to drive maximum results. Under his leadership, Space-O has won the 8th GESIA annual award for being the best mobile app development company. So far, he has validated more than 300 app ideas and successfully delivered 100 custom solutions using the technologies, such as Swift, Kotlin, React Native, Flutter, PHP, RoR, IoT, AI, NFC, AR/VR, Blockchain, NFT, and more.