【发布时间】:2020-03-05 07:23:01
【问题描述】:
我使用的是 Xcode 版本 11.3.1 (11C504)
我正在尝试在 Swift 中创建一个通用函数,该函数将拒绝它的 参数,除非这样的参数是可选的。
在下面的代码中,我期望系统在test()内部对onlyCallableByAnOptable()的所有调用中报告错误,因为它们都没有提供可选值作为参数。
但是,如果我删除符合Optable 的Optional 扩展名,系统只会报告不符合协议!
对我来说,这意味着系统将任何和所有值视为Optional,无论如何!
我做错了吗?
(顺便说一下,在早期版本的 Swift 中,以下代码曾经按预期工作。我最近发现它停止工作,因为它让非Optional 通过。)
protocol Optable {
func opt()
}
func onlyCallableByAnOptable<T>( _ value: T) -> T where T: Optable {
return value
}
// Comment the following line to get the errors
extension Optional: Optable { func opt() {} }
class TestOptable {
static func test()
{
let c = UIColor.blue
let s = "hi"
let i = Int(1)
if let o = onlyCallableByAnOptable(c) { print("color \(o)") }
//^ expected ERROR: Argument type 'UIColor' does not conform to expected type 'Optable'
if let o = onlyCallableByAnOptable(s) { print("string \(o)") }
//^ expected ERROR: Argument type 'String' does not conform to expected type 'Optable'
if let o = onlyCallableByAnOptable(i) { print("integer \(o)") }
//^ expected ERROR: Argument type 'Int' does not conform to expected type 'Optable'
}
}
【问题讨论】:
标签: swift swift-protocols swift-optionals