DEV Community

Cover image for Swift 5.7: Regex. Shorthands for optional unwrapping. Unlock existentials for all protocols.
Sergey Leschev
Sergey Leschev

Posted on • Updated on

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

Shorthands for optional unwrapping

if let workingDirectoryMailmapURL {
    print (workingDirectoryMailmapURL)
}

while let workingDirectoryMailmapURL {
    print (workingDirectoryMailmapURL)
    break
}

guard let workingDirectoryMailmapURL else {
    return
}

print (workingDirectoryMailmapURL)
Enter fullscreen mode Exit fullscreen mode

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"
    }
}
Enter fullscreen mode Exit fullscreen mode

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)
    }
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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


Contacts
I have a clear focus on time-to-market and don't prioritize technical debt. And I took part in the Pre-Sale/RFX activity as a System Architect, assessment efforts for Mobile (iOS-Swift, Android-Kotlin), Frontend (React-TypeScript) and Backend (NodeJS-.NET-PHP-Kafka-SQL-NoSQL). And I also formed the work of Pre-Sale as a CTO from Opportunity to Proposal via knowledge transfer to Successful Delivery.

🛩️ #startups #management #cto #swift #typescript #database
📧 Email: sergey.leschev@gmail.com
👋 LinkedIn: https://linkedin.com/in/sergeyleschev/
👋 LeetCode: https://leetcode.com/sergeyleschev/
👋 Twitter: https://twitter.com/sergeyleschev
👋 Github: https://github.com/sergeyleschev
🌎 Website: https://sergeyleschev.github.io
🌎 Reddit: https://reddit.com/user/sergeyleschev
🌎 Quora: https://quora.com/sergey-leschev
🌎 Medium: https://medium.com/@sergeyleschev
🖨️ PDF Design Patterns: Download

Top comments (1)

Collapse
 
Sloan, the sloth mascot
Comment deleted