示例工程 07-optionals

07-optionals/Sources/Ch07Kit/OptionalTransforms.swift

swift · 1.7 KB

/// map、flatMap、compactMap 的区别:是否剥掉一层 Optional。
public enum OptionalTransforms {
    /// Optional.map 变换内部值,不改变「有没有值」。
    public static func increment(_ value: Int?) -> Int? {
        value.map { $0 + 1 }
    }
 
    /// Optional.map 的结果会嵌套:`String?` 经 `Int.init` 得到 `Int??`。
    public static func nestedParse(_ text: String?) -> Int?? {
        text.map(Int.init)
    }
 
    /// flatMap 剥掉一层,得到 `Int?`。
    public static func flattenedParse(_ text: String?) -> Int? {
        text.flatMap(Int.init)
    }
 
    /// 集合上的 compactMap 同时做变换与过滤。
    public static func parseAll(_ values: [String]) -> [Int] {
        values.compactMap(Int.init)
    }
 
    /// 数组里的 Optional 不经过 compactMap 会保留 nil。
    public static func rawParse(_ values: [String]) -> [Int?] {
        values.map(Int.init)
    }
}
 
public enum ParseError: Error, Equatable {
    case empty
    case notANumber(String)
}
 
/// `try?` 会把错误压成 nil,`do/catch` 能保留原因。
public enum ErrorLoss {
    public static func parse(_ text: String) throws -> Int {
        guard !text.isEmpty else { throw ParseError.empty }
        guard let value = Int(text) else { throw ParseError.notANumber(text) }
        return value
    }
 
    public static func withTryQuestion(_ text: String) -> Int? {
        try? parse(text)
    }
 
    public static func reason(_ text: String) -> String {
        do {
            _ = try parse(text)
            return "ok"
        } catch ParseError.empty {
            return "empty"
        } catch ParseError.notANumber(let raw) {
            return "notANumber(\(raw))"
        } catch {
            return "other"
        }
    }
}