这是将属性标识为"@Published"的适当协议约束



我想为集合中的对象建立一个绑定,这样我就可以像引用指针一样将其传递到下游。我希望这是一个方便的功能,但我遇到了一些麻烦。

我可以对以下协议"Diskable"设置什么约束(如果有的话(来消除下面的错误?

final class PropertiesData: ObservableObject, Diskable {

@Published var fetchedItems: [Property] = []

var location: URL {
let file = try! LocalStorage.rootFolder.createFileIfNeeded(withName: "properties.data")
return file.url
}
}
extension Diskable where T: Identifiable {

func binding(for object: T) -> Binding<T> {
let index = fetchedItems.firstIndex(where: { $0.id == object.id } )!
return $fetchedItems[index] // cannot find 'fetchedItems' in scope
}
}
protocol Diskable: AnyObject {
associatedtype T: Codable
var location: URL { get }
var fetchedItems: [T] { get set }
}

就我所能复制的代码而言,这里有一个解决方案(用Xcode 12.1/iOS 14.1测试(

extension Diskable where T: Identifiable {
func binding(for object: T) -> Binding<T> {
let index = fetchedItems.firstIndex(where: { $0.id == object.id } )!
return Binding(
get: { self.fetchedItems[index] },
set: { self.fetchedItems[index] = $0 }
)
}
}

相关内容

  • 没有找到相关文章

最新更新