雨燕2.2:不能转换类型的值'[B]“指定类型”[A]“ [英] Swift 2.2: cannot convert value of type '[B]' to specified type '[A]'

查看:178
本文介绍了雨燕2.2:不能转换类型的值'[B]“指定类型”[A]“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正式困惑,为什么这不工作(没有太多在这里解释):

 协议A {    VAR值:诠释得{}设置
}结构A:A {    VAR值:诠释
}让数组:[B] = [B(价值:10)让singleAValue:[0] //提取作品如预期A =阵列VAR protocolArray:[A] = []
protocolArray.append(singleAValue)//我们可以把`protocolArray`里面的价值没有问题
打印(protocolArray)让newProtocolArray:[A] =阵列//但为什么这种转换不工作?


解决方案

协议类型的阵列有不同的记忆重新presentation比 B的数组结构。因为 A 数组可以包含多个不同类型的对象,编译器创建一个间接(数组中的元素周围的包装),以确保它们都具有相同的大小。

由于这种转换可能代价高昂(如果源数组是大),编译器会强迫你做它明确由源阵列上的映射。您可以一次将这样的:

 让newProtocolArray = array.map {$ 0作为A}

或本

 让newProtocolArray:[A] = array.map {$ 0}

两者是相等的。

I'm officially confused why this is not working (there isn't much to explain here):

protocol A {

    var value: Int { get set }
}

struct B: A {

    var value: Int
}

let array: [B] = [B(value: 10)]

let singleAValue: A = array[0] // extracting works as expected

var protocolArray: [A] = []
protocolArray.append(singleAValue) // we can put the value inside the `protocolArray` without problems
print(protocolArray)

let newProtocolArray: [A] = array // but why does this conversion not work?

解决方案

The array of the protocol type has a different memory representation than an array of B structs. Because an array of A can contain many different types of objects, the compiler has to create an indirection (a wrapper around the elements in the array) to ensure that they all have the same size.

Since this conversion is potentially costly (if the source array is large), the compiler forces you to make it explicit by mapping over the source array. You can write either this:

let newProtocolArray = array.map { $0 as A }

or this:

let newProtocolArray: [A] = array.map { $0 }

Both are equivalent.

这篇关于雨燕2.2:不能转换类型的值'[B]“指定类型”[A]“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆