Skip to content

Instantly share code, notes, and snippets.

@Josscii
Last active May 5, 2020 01:04
Show Gist options
  • Save Josscii/1fe0b576b1e344aa1734a885091ab15f to your computer and use it in GitHub Desktop.
Save Josscii/1fe0b576b1e344aa1734a885091ab15f to your computer and use it in GitHub Desktop.
读 SwiftBySundell blog 学到的小技巧,截止2020.5.5,大部分内容已经快速过完

SwiftBySundell 阅读笔记

Writing small utility functions in Swift

func configure<T>(
    _ value: T,
    using closure: (inout T) throws -> Void
) rethrows -> T {
    var value = value
    try closure(&value)
    return value
}

Extending optionals in Swift

extension Optional where Wrapped: Collection {
    var isNilOrEmpty: Bool {
        return self?.isEmpty ?? true
    }
}

extension Optional {
    func matching(_ predicate: (Wrapped) -> Bool) -> Wrapped? {
        guard let value = self else {
            return nil
        }

        guard predicate(value) else {
            return nil
        }

        return value
    }
}

Passing key paths as functions

struct Movie {
    var name: String
    var isFavorite: Bool
    ...
}

let movies: [Movie] = loadMovies()

// Equivalent to movies.map { $0.name }
let movieNames = movies.map(\.name)

// Equivalent to movies.filter { $0.isFavorite }
let favoriteMovies = movies.filter(\.isFavorite)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment