从Result <t>转换为无关类型T时崩溃始终失败

时间:2018-01-30 14:58:15

标签: ios swift casting crash

当我将singleResult(类型Result<FAQResult>)投射到FAQResult

时,我遇到了崩溃
fileprivate var fAQS = [FAQ]()

 when(resolved: task).then { (result) -> Void in
       let singleResult:Result<FAQResult> = result.first!     
       let whereItCrashes = singleResult as! FAQResult
       self.fAQS =  whereItCrashes.result!
    }
  

从结果&lt; FAQResult&gt;投射不相关的类型FAQResult总是失败

下面的代码来自项目中使用的核心承诺pod。所有这一切都给了我一个.boolValue,但我需要转换它 对FAQResult的结果。

    public enum Result<T> {
    /// Fulfillment
    case fulfilled(T)
    /// Rejection
    case rejected(Error)

    init(_ resolution: Resolution<T>) {
        switch resolution {
        case .fulfilled(let value):
            self = .fulfilled(value)
        case .rejected(let error, _):
            self = .rejected(error)
        }
    }

    /**
     - Returns: `true` if the result is `fulfilled` or `false` if it is `rejected`.
     */
    public var boolValue: Bool {
        switch self {
        case .fulfilled:
            return true
        case .rejected:
            return false
        }
    }
}

有关如何正确投射的任何解决方案吗?

1 个答案:

答案 0 :(得分:0)

您可以将新的计算属性value添加到Result<T>,如下所示:

/**
 - Returns: actual fulfilled `value` if the result is `fulfilled` or `nil` if it is `rejected`.
*/
public var value: T? {
    switch self {
    case .fulfilled(let value):
        return value
    case .rejected:
        return nil
    }
}

然后singleResult.value会返回FAQResult