当将Int成员的元组分配给Int符合的(异构)协议类型的元组时,似乎只允许通过显式的逐个成员赋值来执行此赋值. protocol MyType {}extension Int: MyType {}let intPair = (1, 2)var myTypePair : (MyType, MyType
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, Int)' to '(MyType, MyType)'
always succeeds <-- well, not really */
if let _ = intPair as? (MyType, MyType) { }
/* warning: conditional cast from '(Int, Int)' to '(MyType, MyType)'
always succeeds */
特点是,对于上面的转换情况,Swift编译器警告说
warning: forced/conditional cast from
'(Int, Int)'
to'(MyType, MyType)'always succeeds
它显然没有:
error: cannot express tuple conversion
'(Int, Int)'
to'(MyType, 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' */
在这种情况下警告是正确的,因为intPair是(Int,Int)符合(MyType,MyType).所以演员阵容将永远成功.由于强类型检查,编译器知道此特定实例将始终成功.
为什么myTypePair = intPair错误是因为myTypePair比intPair更通用,更具体.因此类型不匹配,因此无法分配.
