示例工程 03-strings-unicode

另有 1 个文件未随站点发布(平台工程、二进制或超过 200KB)。

03-strings-unicode/Sources/Ch03Kit/FormatLab.swift

swift · 1.9 KB

import Foundation
 
/// 格式化与本地化:同一个数值在不同 locale、不同格式样式下输出不同。
public enum FormatLab {
    public static let zhCN = Locale(identifier: "zh_CN")
 
    public static func groupedInteger(_ value: Int) -> String {
        value.formatted(.number.locale(zhCN).grouping(.automatic))
    }
 
    public static func fixedDecimal(_ value: Double, fractionDigits: Int) -> String {
        value.formatted(
            .number
                .locale(zhCN)
                .precision(.fractionLength(fractionDigits))
                .grouping(.automatic)
        )
    }
 
    public static func percent(_ ratio: Double) -> String {
        ratio.formatted(.percent.locale(zhCN).precision(.fractionLength(1)))
    }
 
    /// 插值里的值类型决定默认格式;需要固定格式时先格式化再插入。
    public static func greeting(name: String, score: Double) -> String {
        let formatted = score.formatted(.number.precision(.fractionLength(1)).locale(zhCN))
        return "\(name):\(formatted)"
    }
}
 
/// Swift 正则字面量:`/.../` 在编译期解析,捕获组带类型。
public enum RegexLab {
    public static func hashtags(in text: String) -> [String] {
        let tags = text.matches(of: /#([\p{L}\p{N}_]+)/).map { String($0.output.1) }
        return Array(Set(tags)).sorted()
    }
 
    public static func redactedNumbers(in text: String) -> String {
        text.replacing(/\d+/, with: "#")
    }
}
 
/// `Substring` 与 `String` 共享存储;离开原字符串前要显式转换,避免延长生命周期。
public enum SubstringLab {
    public static func csvFields(_ line: String) -> [String] {
        line.split(separator: ",", omittingEmptySubsequences: false).map {
            String($0).trimmingCharacters(in: .whitespaces)
        }
    }
 
    public static func firstWord(_ line: String) -> String {
        line.split(separator: " ").first.map(String.init) ?? ""
    }
}