swift - 根据其出现替换数组包含

标签 swift

如何用数组中对应的字母字符替换数字字符串。

Example:
["1","2","3","3","2","3"]

Replace: 1 -> A, 2-> B, 3-> C

Result should be 
["A","B","C","C","B","C"]

最佳答案

您可以使用 Dictionary 来替换规则:

let array = ["1", "2", "3", "3", "2", "3"]

let replacementRules = ["1": "A", "2": "B", "3": "C"]

let result = array.map{replacementRules[$0] ?? $0}
print(result)
//["A", "B", "C", "C", "B", "C"]

关于swift - 根据其出现替换数组包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38783476/

相关文章:

ios - 如何解决UITextView中的 "auto-scroll"?

ios - NSTextAttachment 上方的可交互 UITextField

ios - 可将表格菜单扩展到 Xcode 中的新 View Controller

ios - 如何以编程方式管理应用程序中的loginViewController?

json - 无法从符合 Equatable 的对象向下转换为 AnyObject

swift - 在 WatchOS 上的 SwiftUI 应用程序中是否可以进行基于页面的导航?

swift - 在 Swift 中打印 CGFloat

ios - 将单个 swift 文件添加到现有的 objective-c 项目

swift - 在 Spritekit 中更改多个级别的状态

ios - 如何在iOS swift3中将模型转换为数组