【问题标题】:Swift/Combine- Assign a filtered object to a property on a classSwift/Combine - 将过滤后的对象分配给类的属性
【发布时间】:2020-07-06 21:41:00
【问题描述】:

我有一个对象列表。

let arr = [[1, 2, 3, 4, 5]]

它存在于存储库中。

class ArrayRepository: ObservableObject { 
     @Published let arr = [1,2,3,4,5]
} 

我有一个类,其属性需要在初始化时分配。

class MyClass: ObservableObject { 
    var id: String = ""
    var myProperty: Int? 
}

我的类是通过一个异步进程创建的,该进程本身就是一个存储库。

class myClassRepository { 
   
    func buildClass -> MyClass { 
        myClassInstance = MyClass()
        self.arrayRepository.$arr.map { arr in 
            arr.filter{ $0 == someOther.Value }
        }.assign(to: \.myProperty, on: myClassInstance).store(in: &subscriptions)
       return myClassInstance
    }
} 

问题是我的模式返回了一个元素数组,我无法使其符合类的奇异属性?最好的方法是什么?

我得到的错误本质上是

Declared closure result '[Int]' is incompatible with contextual type 'Int??'

【问题讨论】:

    标签: ios swift swiftui ios11 combine


    【解决方案1】:

    由于 Swift 类型系统的限制,您目前不能将 assign 设置为具有非 Optional 值的 Optional 属性。但是,您可以创建自己的 assign 版本:

    func assign<Root: AnyObject>(to path: ReferenceWritableKeyPath<Root, Output?>, on root: Root) -> AnyCancellable {
        sink { [weak root] in root?[keyPath: path] = $0 }
    }
    

    此实现还具有防止引用循环的好处。

    【讨论】:

    • 啊,明白了。感谢您的提示!
    猜你喜欢
    • 2020-05-22
    • 2014-04-05
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 2011-09-22
    • 2020-04-21
    • 2010-11-15
    • 2016-01-15
    相关资源
    最近更新 更多