当将Int成员的元组分配给Int符合的(异构)协议类型的元组时,似乎只允许通过显式的逐个成员赋值来执行此赋值.
protocol MyType {} extension Int: MyType {} let intPair = (1,2) var myTypePair : (MyType,MyType) // OK myTypePair = (intPair.0,intPair.1) // OK let intPairToMyTypePair : ((Int,Int)) -> (MyType,MyType) = { ($0.0,$0.1) } myTypePair = intPairToMyTypePair(intPair) // For all below: // "Error: cannot express tuple conversion '(Int,Int)' to '(MyType,MyType)'" myTypePair = intPair myTypePair = (intPair as! (MyType,MyType)) /* warning: forced cast from '(Int,MyType)' always succeeds <-- well,not really */ if let _ = intPair as? (MyType,MyType) { } /* warning: conditional cast from '(Int,MyType)' always succeeds */
特点是,对于上面的转换情况,Swift编译器警告说
warning: forced/conditional cast from
'(Int,Int)'
to'(MyType,MyType)'
always succeeds
它显然没有:
error: cannot express tuple conversion
'(Int,MyType)'
问题:这里的问题是,是否按预期不允许直接转让?如果是这样,怎么了警告信息,铸件将永远成功?
(编辑补充)
为了进一步澄清我在这里要求的特殊行为:我想知道为什么即使Swift警告我们“是”的情况总是如此,以下片段也会打印出“bar”:
let intPair = (1,2) switch intPair { case is (MyType,MyType): print("foo") /* warning: 'is' test is always true */ case _ : print("bar") } // "bar"
数组的类似情况很简单,有解释错误,但我不知道这是否是一个有效的比较,因为元组更多是匿名结构而不是某些表兄.
let intArr = [Int](1...5) var myTypeArr : [MyType] myTypeArr = intArr /* error: cannot assign value of type '[Int]' to type '[MyType]' */ if let _ = intArr as? [MyType] { } /* error: 'MyType' is not a subtype of 'Int' */
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。