加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 分配关联类型的元组,为什么只允许通过显式的逐个成员分

发布时间:2020-12-14 04:30:26 所属栏目:百科 来源:网络整理
导读:当将Int成员的元组分配给Int符合的(异构)协议类型的元组时,似乎只允许通过显式的逐个成员赋值来执行此赋值. protocol MyType {}extension Int: MyType {}let intPair = (1,2)var myTypePair : (MyType,MyType)// OKmyTypePair = (intPair.0,intPair.1)// OKl
当将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' */

解决方法

在这种情况下警告是正确的,因为intPair是(Int,Int)符合(MyType,MyType).所以演员阵容将永远成功.由于强类型检查,编译器知道此特定实例将始终成功.

为什么myTypePair = intPair错误是因为myTypePair比intPair更通用,更具体.因此类型不匹配,因此无法分配.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读