Swift New Changes (Code) - Imtiaz211/interviews GitHub Wiki

Swift New features 5.7

  • if let shorthand for unwrapping optionals
         var name: String? = "Linda"
        if let name {
        print("Hello, \(name)!")
        }
  • Multi-statement closure type inference
let scores = [100, 80, 85]
let results = scores.map { score in // Here return type no need to specify
    if score >= 85 {
        return "\(score)%: Pass"
    } else {
        return "\(score)%: Fail"
    }
}
  • Clock, Instant, and Duration
let clock = ContinuousClock()
let time = clock.measure {
    // complex work here
}
print("Took \(time.components.seconds) seconds")
  • Regular expressions
let message = "the cat sat on the mat"
print(message.ranges(of: "at"))
print(message.replacing("cat", with: "dog"))
print(message.trimmingPrefix("the "))

do {
    let atSearch = try Regex("[a-z]at")
    print(message.ranges(of: atSearch))
} catch {
    print("Failed to create regex")
}

let search1 = /My name is (.+?) and I'm (\d+) years old./
let greeting1 = "My name is Taylor and I'm 26 years old."

if let result = try? search1.wholeMatch(in: greeting1) {
    print("Name: \(result.1)")
    print("Age: \(result.2)")
}
  • Type inference from default expressions
func drawLotto1<T: Sequence>(from options: T, count: Int = 7) -> [T.Element] {
    Array(options.shuffled().prefix(count))
}
  • Concurrency in top-level code
import Foundation
let url = URL(string: "https://hws.dev/readings.json")!
let (data, _) = try await URLSession.shared.data(from: url)
let readings = try JSONDecoder().decode([Double].self, from: data)
print("Found \(readings.count) temperature readings")
  • Opaque parameter declarations
func isSorted(array: [some Comparable]) -> Bool {
    array == array.sorted()
}
  • Unlock existentials for all protocols
let firstName: any Equatable = "Paul"
let lastName: any Equatable = "Hudson"
  • Lightweight same-type requirements for primary associated types
protocol Cache<Content> {
    associatedtype Content

    var items: [Content] { get set }

    init(items: [Content])
    mutating func add(item: Content)
}
⚠️ **GitHub.com Fallback** ⚠️