Weekly Swift articles, podcasts and tips by John Sundell.

Omitting the return keyword

Published on 14 Oct 2019

New in Swift 5.1: The return keyword can now be omitted when declaring functions and computed properties that only contain a single expression, which is really nice when declaring simpler convenience APIs:

extension MarkdownReader {
    var isAtStart: Bool { index == string.startIndex }
    var didReachEnd: Bool { index == string.endIndex }
    var currentCharacter: Character { string[index] }
    
    func encodeCurrentCharacter() -> String {
        currentCharacter.encoded()
    }
}

While this new behavior might take a little while to get used to, it matches the way closures work, which does result in improved consistency between properties, methods, and closures:

// Here's how the above 'isAtStart' property might have been
// declared as a closure instead, prior to Swift 5.1:
let isAtStart: () -> Bool = { index == string.startIndex }