BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Swift 4.1 Enhances Generics, Compiler Optimizations, and Package Manager

Swift 4.1 Enhances Generics, Compiler Optimizations, and Package Manager

Bookmarks

Swift 4.1 is now officially available, bringing new language features, build options, and several enhancements to the Swift Package Manager and Foundation.

As InfoQ previously reported, when Swift 4.1 became preliminarily available in Xcode 9.3 beta, the most significant new feature at the language level is conditional conformance, which allows a developer to specify that a generic type conforms to a protocol only if its type parameters satisfy given requirements. This is mostly important in view of the possibility of defining generic adapter types, i.e., generic types that reflect the capabilities of the composing types, such as a collection type that exposes a part of the API of its component type.

Another powerful extension to generic types in Swift 4.1 is provided by the possibility of specifying recursive constraints on associated types. Associated types in Swift are used in protocol specifications as placeholders for a type that is not known, and instead will be provided when the protocol is adopted. For example, here is a Container protocol using an Item associated type:

protocol Container {
    associatedtype Item
    mutating func append(_ item: Item)
    var count: Int { get }
    subscript(i: Int) -> Item { get }
}

Optionally, Item may be constrained to a specific type or protocol, e.g.:

protocol Container {
    associatedtype Item : Bar
    ...
}

Previous to Swift 4.1, the type or protocol constraint for an associated type could not recursively refer to the protocol being defined. Swift 4.1 lifts that restriction, thus allowing the following recursive protocol:

protocol Container {
    associatedtype Item : Container
    ...
}

Other new language features in Swift 4.1 worth mentioning are:

On the compiler front, Swift 4.1 now supports a code size optimization mode in addition to the already supported optimization for speed. The new optimization option works both in whole-module as well as in single-file compilation mode, with the former providing the best results. According to Apple, this may reduce code size from 5% to 30% for some projects.

Finally, Swift 4.1 brings enhancements to the Package Manager. Namely, it now correctly resolves dependencies in package graphs that use different protocols, such as ssh and http. Additionally, it is now faster handling shared dependencies.

Swift 4.1 is available in Xcode 9.3 on macOS, while official binaries are available for Ubuntu.

Rate this Article

Adoption
Style

BT