ios - 在 Swift 中将结构重构为枚举
问题描述
今天有人评论了这段代码,并建议它会更好enum
:
typealias PolicyType = (filename: String, text: String)
struct Policy {
static let first = PolicyType(filename: "firstFile.txt", text: "text in first file")
static let second = PolicyType(filename: "secondFile.txt", text: "text in second file")
static let third = PolicyType(filename: "thirdFile.txt", text: "text in third file")
}
let thirdPolicyText = Policy.third.text
有没有一种更高效、更可维护的方式来使用枚举来做到这一点?我的主要目标是可维护性。
以下是我想出的:
enum Policy: RawRepresentable {
case one
case two
case three
var rawValue: (filename: String, text: String) {
switch self {
case .one:
return ("1", "policy 1 text")
case .two:
return ("2", "policy 2 text")
case .three:
return ("3", "policy 3 text")
}
}
init?(rawValue: (filename: String, text: String)) {
switch rawValue {
case ("1", "policy 1 text"):
self = .one
case ("2", "policy 2 text"):
self = .two
case ("3", "policy 3 text"):
self = .three
default:
return nil
}
}
}
至此,我已经弄清楚如何使用 astruct
和 an实现类似的功能enum
。如果有人回去更新它,这enum
似乎需要更多的维护,而且更容易出错。Paul Hegarty 说不会崩溃的线路是你不写的线路,而且enum
路线看起来和感觉都很麻烦。
enum
走这条路线与一条路线相比有记忆优势struct
吗?
完成后,我希望能够将 Policy 作为参数传递,如下所示:
func test(for policy: Policy) {
print(policy.rawValue.filename)
print(policy.rawValue.text)
}
test(for: Policy.first)
解决方案
这是一种可能性。它有点长,但它是 Swifty:
enum Policy {
case one, two, three
var filename: String {
switch self {
case .one: return "Policy 1 name"
case .two: return "Policy 2 name"
case .three: return "Policy 3 name"
}
}
var text: String {
switch self {
case .one: return "Policy 1 text"
case .two: return "Policy 2 text"
case .three: return "Policy 3 text"
}
}
}
目前 Swift 枚举的问题在于它们仅限于 RawValues。我最近遇到了和你类似的情况,我也尝试使用枚举而不是结构。我什至尝试了一个命名元组。但是,我最终使用了一个结构。
推荐阅读
- angular - AG Grid - CellRender - 读取复选框值
- symfony - FOSRestBundle 和 Pagerfanta
- bazel - 如何通过 Starlark 从 usr/bin 中“正确”调用可执行文件?
- css - 防止 iframe 在 iOS 上调整其自身内容的高度
- javascript - Javascript - 上传前的图像预览。在同一页面上的多个实例上需要
- google-app-engine - 在“gcloud app logs tail”流中获取“/dev/log”
- sql - 将小时/分钟转换为现有时间戳时,日期时间或间隔的 SQL 操作无效
- julia - 在 Julia 中为 LU 分解构建递归函数
- python - 如何授予 cv2.VideoWriter 权限 python
- symfony - symfony 没有找到“GET”的路由