【发布时间】:2018-01-12 10:58:08
【问题描述】:
我想把一个 swift 3 do-catch 放在一个函数中,而不是在我需要的地方不断地写它;在这个函数中,我希望返回一个带有布尔值的tuple,以及一个可选的错误。
我正在尝试从函数返回一个元组并在我的 XCTest 中处理结果
但是,我收到一条错误消息:
条件绑定的初始化程序必须具有 Optional 类型,而不是 '(Bool, Error?)'(又名 '(Bool, Optional)')
我的功能如下;
public static func isValidPurchase(train: Train, player: Player) -> (Bool, Error?) {
do {
let result = try train.canBePurchased(by: player)
return (result, nil)
} catch let error {
return (false, error)
}
}
我的canBePurchased 代码有点长,但它是这样的:
func canBePurchased(by player: Player) throws -> Bool {
if (!self.isUnlocked) {
throw ErrorCode.trainIsNotUnlocked(train: self)
}
// other if-statements and throws go here
}
在我的 XCTest 中,我这样称呼它:
if let result = TrainAPI.isValidPurchase(train: firstTrain, player: firstPlayer) as! (Bool, Error?) {
}
我试过强制转换:
if let result: (Bool, Error?) ...
但这只会将编译器错误降级为警告。
编译器显示上述错误。
我在Initializer for conditional binding must have Optional type 方面做错了什么,我该如何避免?
谢谢
【问题讨论】:
标签: swift tuples optional do-catch