gpt4 book ai didi

swift - 我可以在协议(protocol)上使用 Swift 的 map() 吗?

转载 作者:行者123 更新时间:2023-11-30 11:43:47 25 4
gpt4 key购买 nike

我有一些模型代码,其中有一些我想要读取和写入 plist 的想法。我有以下代码:

protocol Note {
var body: String { get }
var author: String { get }
var favorite: Bool { get set }
var creationDate: Date { get }
var id: UUID { get }
var plistRepresentation: [String: Any] { get }
init(plist: [String: Any])
}

struct Thought: Note {
let body: String
let author: String
var favorite: Bool
let creationDate: Date
let id: UUID
}

extension Thought {
var plistRepresentation: [String: Any] {
return [
"body": body as Any,
"author": author as Any,
"favorite": favorite as Any,
"creationDate": creationDate as Any,
"id": id.uuidString as Any
]
}

init(plist: [String: Any]) {
body = plist["body"] as! String
author = plist["author"] as! String
favorite = plist["favorite"] as! Bool
creationDate = plist["creationDate"] as! Date
id = UUID(uuidString: plist["id"] as! String)!
}
}

对于我的数据模型,然后在我的数据写入 Controller 中我有这个方法:

func fetchNotes() -> [Note] {
guard let notePlists = NSArray(contentsOf: notesFileURL) as? [[String: Any]] else {
return []
}
return notePlists.map(Note.init(plist:))
}

出于某种原因,行 return notePlists.map(Note.init(plist:)) 给出错误 'map' 生成 '[T]',而不是预期的上下文结果类型'[注意]'但是,如果我用 return notePlists.map(Thought.init(plist:)) 替换该行,我就没有问题了。显然我无法映射协议(protocol)的初始值设定项?为什么不呢?替代解决方案是什么?

最佳答案

如果您期望有多种符合注释的类型,并且想知道它存储在字典中的注释类型,您需要将所有注释类型的枚举添加到您的协议(protocol)中。

enum NoteType {
case thought
}

将其添加到您的协议(protocol)中。

protocol Note {
var noteType: NoteType { get }
// ...
}

并将其添加到您的 Note 对象中:

 struct Thought: Note {
let noteType: NoteType = .thought
// ...
}

这样您就可以从字典中读取此属性并进行相应的映射。

关于swift - 我可以在协议(protocol)上使用 Swift 的 map() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49061915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com