具有非可选值的空可变属性

时间:2016-06-19 18:13:47

标签: swift swift2 reactive-cocoa

我可以使用非可选值创建空的可变属性(或其他类型的属性)吗?

例如,这是有效的:

let distributions = MutableProperty<Distributions?>(nil)

但我需要这样的事情:

let distributions = MutableProperty<Distributions>()

分发对象:

struct Distributions : CollectionType{

    typealias Index = Int

    private let distributions : [Distribution]

    init(distributions : [Distribution]){
        self.distributions = distributions
    }

    var startIndex: Int {
        return 0
    }

    var endIndex: Int {
        return distributions.count
    }

    subscript(i: Int) -> Distribution {
        return distributions[i]
    }

}

struct Distribution{
    let id : Int
    let dateStart : String
    let dateEnd : String
}

Thnx寻求帮助。

1 个答案:

答案 0 :(得分:2)

我可以想到两种方法可以做到这一点。一,在信号发生器上使用ignoreNil

let distributions = MutableProperty<Distributions?>(nil)

distributions.producer
    .ignoreNil()
    .startWithNext { distributions in
        // distributions is of type [Distribution]
    }

二,将MutableProperty的初始值设置为空的Distributions对象。

let distributions = MutableProperty<Distributions>(Distributions(distributions: []))

// You can skip the initial value if need be
distributions.producer.skip(1)