Swift is one of the major development languages for Apple platforms, and the release of its fourth generation happened only recently. So far, the public beta version has been released; the release date of Swift 4.0 has not yet been officially announced, but is scheduled for fall 2017.
To date, Swift 4 is known to be the most stabilized version of this language, which would combine all the best features of previous versions (both in the language kernel and attached libraries). In its development, special attention is paid to the compatibility of sources with the Swift 3 code, as well as the direct provision of ABI stability.
In this article, we are going to overview the main changes in Swift 4, presented in the form of "evolutions" - proposals for the updated version. Each proposal is indicated by a “SE” prefix and a four-digit numeral. So, what's new in Swift 4?
New Features in Swift 4
- Compatibility of the Swift 4 compiler with Swift 3 via the ‘@available’ attribute. One of the fundamental concepts of Swift 4 is the guarantee of Swift 3 source code stability. It is important to note that the transition from Swift 3 to 4 will be much less cumbersome than from version 2.2 to 3. In general, the overwhelming changes are additive, and do not represent a complete rethinking of the previous Swift versions’ operating principles (which, in turn, do not entail the need for manual migration of apps created for earlier platforms). The Swift migration tool helps to implement most of the custom innovations into existing projects.
- Binary compatibility between applications and libraries via Swift 4 ABI. One of the main initially declared attributes of the new Swift is its maximum compatibility with other versions. That's why the Swift 4 developers thought out the mechanisms for ensuring the stability of ABI which, in turn, determines the binary compatibility between applications and libraries that are compiled with different versions of Swift.
- Advanced string type behavior. The string in Swift 4 has been advanced greatly, and String API got a complete overhaul while maintaining compatibility with earlier versions. In Swift version 4, strings are char collections, same as it was in the Swift 1.x versions. Thus, the functionality of ‘String.CharacterView’ is now only directed to the parent type. In addition, the SE-0168 proposal describes the newly introduced simplified syntax for declaring multi-line string literals. Now, developers do not need to shield single quotes which, in turn, determines the simplest possible use of JSON and HTML formats. This was done to simplify the presentation of texts and eliminate the need for manual line partitioning with the help of concatenation operators, as such forced actions sometimes resulted in the deceleration of the compilation process. SE-0163 has not undergone the final approval yet, so a future release of Swift 4 may have some additions and upgrades to string operations.
The below code demonstrates the per character string printout:
Due to strings considered as both sequence and collection, such methods as ‘count’, ‘isEmpty’, ‘dropFirst()’ and ‘reversed’ also apply to them.
- Convenient source declarations. Swift 4 will use strongly typed smart keys in the form of uninvoked property references, which represent a fundamentally new model of key paths, described in detail in SE-0161. These types of key paths are more convenient than normal strings, which imposed a number of problems on developers such as loss of type data (and, therefore, the need to use the extremely inconvenient Any API), poor readability, applicability to NSObjects and Darwin platforms, exclusively. In addition, the smart path keys allow the use of subscript notations. In general, they provide a new level of convenience in working with collections, arrays, and dictionaries. Note that the SE-0161 proposal has not been implemented yet, and by the time the Swift 4 is launched publicly, it may still undergo several modifications.
- Better readability of the code that contains indexed objects (the possibility for one-way indexing). The SE-0172 proposal adds a new ‘RangeExpression’ protocol, as well as a set of prefix/postfix operators to define one-way ranges in which it is impossible to pre-determine either the lower or upper boundaries. For this, developers can use one-way sequences (the most frequent example of using this indexing method is an infinite sequence). Introducing a more flexible alternative to the traditional ‘enumerated()’ function, these tools allow for the creation of sequences, the indexes of which start at zero.
- Improvements to dictionaries and sets. The SE-0165 proposal adds a number of improvements to the dictionary and set. Together, these additions help to solve the problems associated with:
- merging initializers and methods (in previous versions of Swift, the description of these processes made the code extremely capacitive);
- iteratively making changes to “key-value” pairs (for this, ‘nil’ is used, which often provokes the appearance of bugs);
- implementing standard ‘map’ and ‘filter’ to dictionaries (instead, the ‘MapValues’ method was created and a new ‘filter’ was defined);
- the inability to reserve the capacity for dictionaries (now this can be done via the ‘capacity’ property and ‘reserveCapacity(_:)’ method); and,
- sequence element grouping (now you can use the ‘Dictionary(grouping:by:)’ initializer to define dictionaries with T-type keys and values like ‘[Iterator.Element]’). Similar changes have also been made to the sets.
- Support for Unicode 9. Swift 4 has complete support for Unicode 9. Thus, the problems of improper grapheme clustering (that is, their interpretation via a string) for modern different hue emojis have been eliminated. In earlier Swift versions, the use of Unicode characters containing a number of code points resulted in a count value greater than 1.
- The decrease in the need to use the ‘fileprivate’ key. The SE-0169 proposal introduces some changes to existing access control rules. For example, in Swift 4, private declarations became visible in the same file parent type extensions. This allows for the breakup of type definitions into multiple extensions, while still using secure access for the most "private" variables and methods.
For instance, in Swift 3 you could write the following code:
Compiling this code, you will get an error message because 'languages' is inaccessible. In Swift 4, however, this is fixed and ‘languages’ is accessible via an extension using the ‘private’ key.
- Archiving and serialization. In Swift 4, there is a significant improvement in the principles of working with the ‘Codable’ protocol, which is a type alias for ‘Encodable’ and ‘Decodable’ protocols. In particular, the SE-0166 proposal describes the ‘enum’ and ‘struct’ types as subjects to archiving and serialization (both types can include methods to pack and unpack themselves using the ‘Codable’ protocol). In addition, SE-0166 is designed to solve the problem associated with the serialization of external formats (such as JSON or plist, for example).
- New encoding and decoding protocols. Besides SE-0166, the developers of Swift 4 introduced the SE-0167 proposal, in which new encoding and decoding protocols are defined (they can be found in ‘NSKeyedArchiver’). In addition, this proposal describes the introduction of new ‘Codable’ types in ‘NSKeyedArchiver’ and ‘NSKeyedUnarchive’.
- A new ‘swapAt’ method for the collection elements swapping. The SE-0173 proposal introduces the new ‘MutableCollection.swapAt(_:_:)’ method, which implements procedures for the exchanging of two collection elements. In contrast to the existing ‘swap(_:_:)’ method, the new one accepts indexes of elements that must be exchanged (via ‘inout’ arguments), not elements themselves. The reason for this innovation is explained by the changes in memory access rules described in the SE-0176 proposal (in particular, now the exchange with two ‘inout’ arguments is not allowed, and ‘swap(_:_:)’ won’t work as intended).
- A ’reduce’ method that returns ‘inout’ value. The SE-0171 proposal introduces a new version of the ‘reduce’ method. Its main feature is the fact that the result of ‘reduce’ is the ‘inout’ value, which is passed to the ‘combine’ function. This correction can significantly speed up the operation of some algorithms, which implements ‘reduce’ for incremental construction of sequences. In particular, due to SE-0171, the need for intermediate results calculation and copying is eliminated. Today, in the Swift 4 beta version, this improvement has not yet been implemented.
- Class and subtype instances. The SE-0156 proposal introduces one of the most useful Objective-C features into Swift. Through instances, developers can assign variables to specific types by binding them to one or more protocols at the same time (while retaining the ability to grant elements of the object the right to belong to other classes or be assigned to ‘AnyObject’).
- Less chance for errors when using ‘NSNumber’. ‘NSNumber’ is a subclass that contains a set of methods for setting values and providing access to ‘char’, ‘short int’, ‘int’, ‘long int’, ‘float’, ‘double’ or ‘bool’ types variables. A very common problem with working with this subclass was the unsafe expression of numeric types values. The proposal SE-0170 was just designed to fix the problem using the downcasting optional ‘as?’.
- The possibility for sub-scripts to accept and return arguments in the form of generics. According to the SE-0148 proposal, sub-scripts can now fully interact with generics (in particular, accept and return arguments in such a form). In previous versions of Swift, sub-scripts could not be identified with generics, which imposed restrictions on the conversion of specialized sub-scripts to universal ones.
Roadmap to Swift 4: Tutorial
As noted previously, migration to Swift 4 is characterized by simplicity and minimal user intervention. In turn, XCode 9 contains the Swift Migrator, which provides a smooth project transfer to Swift 4. To learn more about Swift migration tools you can review the full guide by the following link: https://swift.org/migration-guide/
All of the above additions for Swift 4 contribute to the creation of "clean" code and also extend some of the features that Swift creators offered in its earlier versions. Therefore, if you are looking for more secure features, less prone to errors, easier to learn programming language for Apple platforms such as Mac OS and iOS, and that helps to create readable and easily understandable code, we can safely say that Swift 4 is what you need!
Read also: Swift vs Objective-C: What to Choose in 2017
If you are still not sure about the benefits of Swift 4 in your project, you can contact us today and request a quote. Our experts will gladly discuss your ideas and methods for project migration to Swift 4 in more detail.