Pull to refresh

Swift 5.7: Regex. Shorthands for optional unwrapping. Unlock existentials for all protocols

Level of difficulty Medium
Reading time 2 min
Views 424
Development for iOS *Development of mobile applications *Swift *
Sandbox

Shorthands for optional unwrapping

if let workingDirectoryMailmapURL {
    print (workingDirectoryMailmapURL)
}

while let workingDirectoryMailmapURL {
    print (workingDirectoryMailmapURL)
    break
}

guard let workingDirectoryMailmapURL else {
    return
}

print (workingDirectoryMailmapURL)

Improved type inference for complex closures

Swift's type inference for closures has improved. It is now able to infer the return type (String) of complex closures like this one:

let scores = [100, 70, 75]

let results = scores.map { score in
    if score >= 75 {
        return "\(score)%: Pass"
    } else {
        return "\(score)%: Fail"
    }
}

Better string parsing with Swift Regex

A regular expression is a powerful tool for pattern matching and string manipulation. Regexes are very compact and sometimes difficult to understand and debug.

import RegexBuilder

if let regex = try? Regex("#[a-zA-Z0-9_]+") {
    let matches = tweet.matches(of: regex)
    for match in matches {
        let hashTag = tweet[match.range.lowerBound ..< match.range.upperBound]
        print (hashTag)
    }
}

Creating a Regex with Regex literal

The easiest way to create a regex would be using a regex literal, as shown below. The regex literal provides compile-time checks. More about regex literals here.

import RegexBuilder

let regex = /#[A-Za-z_0-9]+/
let matches = tweet.matches(of: regex)

for match in matches {
    let hashTag = tweet[match.range.lowerBound ..<   match.range.upperBound]
    print (hashTag)
}

Creating a Regex using RegexBuilder

This provides an expressive result-builder-based, domain-specific language to build regular expressions, very similar to SwiftUI.

import RegexBuilder

let regex = Regex {
    "#"
    OneOrMore {
        CharacterClass(
            ("a" ... "z"),
            ("0" ... "9"),
            ("_" ... "_")
        )
    }
}

let matches = tweet.matches(of: regex)

for match in matches {
    let hashTag = tweet[match.range.lowerBound ..< match.range.upperBound]
    print (hashTag)
}

Unlock existentials for all protocols

Swift 5.7 significantly loosens the Swift's ban on using protocols as types when they have associated type requirements. In simple terms, this means the following code becomes legal:

let tvShow: [any Equatable] = ["Brooklyn", 99]

Swift Regex Literals
Implemented: Swift 5.7
https://github.com/sergeyleschev/swift-evolution/blob/main/proposals/0354-regex-literals.md

Tags:
Hubs:
Rating 0
Comments 0
Comments Leave a comment

Posts