【问题标题】:Which is an appropriate protocol constraint to identify a property as being '@Published'这是将属性标识为“@Published”的适当协议约束
【发布时间】:2020-12-26 12:17:59
【问题描述】:

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

如果有的话,我可以使用以下协议“可磁盘”来消除我遇到的错误吗?

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 }
}

【问题讨论】:

    标签: swiftui combine protocol-extension


    【解决方案1】:

    我可以在这里复制您的代码是一个解决方案(使用 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 }
            )
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多