Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SwiftUI:数组的扩展,用于获取数组实例的绑定_Swift_Swiftui - Fatal编程技术网

SwiftUI:数组的扩展,用于获取数组实例的绑定

SwiftUI:数组的扩展,用于获取数组实例的绑定,swift,swiftui,Swift,Swiftui,我想在数组上有一个扩展,它基本上返回一个绑定。 这样做的目的是为了在详细视图中创建一个绑定,该绑定是从列表的导航链接调用的 以下是我目前得到的信息: 扩展数组,其中元素:可识别{ mutating func getBinding(实例:元素)->Binding{ 如果let index=self.firstIndex(其中:{$0.id==instance.id}){ 返回绑定( 获取:{self[index]},//错误 集合:{self[index]=$0})//错误 }否则{ fatalE

我想在
数组
上有一个扩展,它基本上返回一个
绑定
。 这样做的目的是为了在
详细视图
中创建一个
绑定
,该绑定是从
列表
导航链接
调用的

以下是我目前得到的信息:

扩展数组,其中元素:可识别{
mutating func getBinding(实例:元素)->Binding{
如果let index=self.firstIndex(其中:{$0.id==instance.id}){
返回绑定(
获取:{self[index]},//错误
集合:{self[index]=$0})//错误
}否则{
fatalError()//在此处实现错误处理
}
}
}
我在指定的位置获得了错误
转义闭包捕获变异的“self”参数。我怎样才能解决这个问题

TL;博士 以下是我如何使用此扩展:

类视图模型:ObserveObject{
@已发布的var项目:[项目]
初始化(带有项:[Item]=[Item]()){
self.items=项目
}
}
结构项:可识别、可散列{
let id:UUID
变量标题:字符串
静态变量sampleItems:[项]{
变量项=[项]()

对于0..中的i,将扩展名更改为:

extension Binding {
    func getBinding<T>(of instance: T) -> Binding<T>
    where Value == [T], T: Identifiable {
        if let index = self.wrappedValue.firstIndex(where: { $0.id == instance.id }) {
            return .init(
                get: { self.wrappedValue[index] }, //error
                set: { self.wrappedValue[index] = $0 }) //error
        } else {
            fatalError() //implement error handling here
        }
    }
}
并将您的
ForEach
更改为:

ForEach(viewModel.items.indices) { index in
    let item = viewModel.items[index]
    NavigationLink(item.title, destination: DetailView(item: $viewModel.items[index]))
}

希望你喜欢:)

Swift是一种类型推断语言
return.init(
Awesome,正如预期的那样工作!@leo我尝试了尽可能少的更改,否则我还可以做一些其他优化。也就是说,你是对的。init工作得更好,所以我更改了代码。谢谢。
ForEach(viewModel.items.indices) { index in
    let item = viewModel.items[index]
    NavigationLink(item.title, destination: DetailView(item: $viewModel.items[index]))
}