ByAI:Swift中ListFormatter的使用指南

1. Swift 语言的强大特性

Swift 是一种功能强大的编程语言,提供了许多内置的便利特性,帮助开发者编写简洁、高效且可读性强的代码。随着每个新版本的发布,Swift 语言不断进化,总有新特性等待开发者探索和学习。

2. ListFormatter 类的引入

最近引起我注意的一个特性是 ListFormatter 类。如果你曾经在 Swift 中处理过列表,并需要将它们连接成一个人类可读的句子,你可能使用过 joined 操作符和一些自定义逻辑来为最后一个项目提供不同的分隔符:

swift

复制

bash 复制代码
let languages = ["Swift", "Kotlin", "Rust"]
let joinedLanguages = languages.dropLast().joined(separator: ", ")
    + (languages.count > 1 ? " and " : "")
    + (languages.last ?? "")
// 输出: "Swift, Kotlin and Rust"

虽然这种实现适用于特定用例,但它不能很好地扩展,因为它没有考虑用户的区域设置和语言。

3. ListFormatter 和 ListFormatStyle 的作用

ListFormatterListFormatStyle 是 Foundation 框架的一部分,提供了一种将项目列表连接成自然且本地化的人类可读句子的方法。

4. 使用 ListFormatter

你可以创建一个 ListFormatter 实例,然后调用 string(from:) 方法将任何项目列表转换为人类可读的句子:

swift

复制

csharp 复制代码
import Foundation

let listFormatter = ListFormatter()
// 输出: "Swift, Kotlin, and Rust"
listFormatter.string(from: ["Swift", "Kotlin", "Rust"])

默认情况下,ListFormatter 类会考虑用户的区域设置。你也可以通过修改格式化器实例的 locale 属性来强制使用特定的区域设置:

swift

复制

csharp 复制代码
import Foundation

let listFormatter = ListFormatter()
listFormatter.locale = Locale(identifier: "es-ES")
// 输出: "Swift, Kotlin y Rust"
listFormatter.string(from: ["Swift", "Kotlin", "Rust"])
5. 支持多种类型

虽然我只使用了字符串数组,但 ListFormatter 并不限制你只能使用字符串。实际上,API 设计为接受任何类型的数组:

swift

复制

swift 复制代码
import CoreFoundation

@available(macOS 10.15, *)
open class ListFormatter : Formatter {
    open func string(from items: [Any]) -> String?
}

需要注意的是,为了使 string 方法产生有意义的结果,项目必须能够表示为字符串。许多类型(如 Int)已经可以表示为字符串,但对于自定义类型,你可能需要遵循 CustomStringConvertible 协议:

swift

复制

less 复制代码
import Foundation

struct Language: CustomStringConvertible {
    let title: String
    
    var description: String {
        return title
    }
}

let listFormatter = ListFormatter()
// 输出: "Swift, Kotlin, and Rust"
listFormatter.string(from: [
    Language(title: "Swift"),
    Language(title: "Kotlin"),
    Language(title: "Rust")
])
6. 使用 formatted 方法

虽然 ListFormatter 很好用,但我更喜欢在列表实例上使用 formatted 方法,因为它更简洁,并提供了进一步的定制选项:

swift

复制

css 复制代码
import Foundation

let languages = ["Swift", "Kotlin", "Rust"]
// 输出: "Swift, Kotlin, and Rust"
languages.formatted()
// 输出: "Swift, Kotlin, or Rust"
languages.formatted(.list(type: .or))
// 输出: "Swift, Kotlin, & Rust"
languages.formatted(.list(type: .and, width: .short))

总结

  • ListFormatter 是一个强大的工具,用于将列表转换为人类可读的句子,并支持本地化。
  • 它不仅可以处理字符串数组,还可以处理任何可以表示为字符串的类型。
  • 通过 formatted 方法,开发者可以更简洁地实现列表格式化,并进一步定制输出格式。

这篇文章展示了如何在 Swift 中利用 ListFormatterformatted 方法来处理列表的本地化和格式化,使得代码更加简洁和可维护。

原文链接

www.polpiella.dev/join-list-o...

相关推荐
初级代码游戏1 天前
iOS开发 SwiftUI 14:ScrollView 滚动视图
ios·swiftui·swift
初级代码游戏1 天前
iOS开发 SwitftUI 13:提示、弹窗、上下文菜单
ios·swiftui·swift·弹窗·消息框
zhyongrui2 天前
托盘删除手势与引导体验修复:滚动冲突、画布消失动画、气泡边框
ios·性能优化·swiftui·swift
zhangfeng11332 天前
CSDN星图 支持大模型微调 trl axolotl Unsloth 趋动云 LLaMA-Factory Unsloth ms-swift 模型训练
服务器·人工智能·swift
zhyongrui3 天前
SnipTrip 发热优化实战:从 60Hz 到 30Hz 的性能之旅
ios·swiftui·swift
大熊猫侯佩3 天前
Neo-Cupertino 档案:撕开 Actor 的伪装,回归 Non-Sendable 的暴力美学
swift·observable·actor·concurrency·sendable·nonsendable·data race
2501_915921435 天前
在没有源码的前提下,怎么对 Swift 做混淆,IPA 混淆
android·开发语言·ios·小程序·uni-app·iphone·swift
00后程序员张5 天前
对比 Ipa Guard 与 Swift Shield 在 iOS 应用安全处理中的使用差异
android·开发语言·ios·小程序·uni-app·iphone·swift
大熊猫侯佩6 天前
星际穿越:SwiftUI 如何让 ForEach 遍历异构数据(Heterogeneous)集合
swiftui·swift·遍历·foreach·any·异构集合·heterogeneous
hjs_deeplearning6 天前
认知篇#15:ms-swift微调中gradient_accumulation_steps和warmup_ratio等参数的意义与设置
开发语言·人工智能·机器学习·swift·vlm