向下铸造多协议阵列<&协议下,P1,P2>>与Array< P1> [英] Down casting multiple protocol Array<protocol<P1, P2>> to Array<P1>

查看:259
本文介绍了向下铸造多协议阵列<&协议下,P1,P2>>与Array< P1>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有两个数组

  VAR arrayOne:数组<&协议下,P1,P2>>
VAR arrayTwo:数组< P1>

其中P1和P2协议。

问题是如何使向下转换操作

  arrayTwo = arrayOne为阵< P1>

我根据X code得到的是:

 无法转换类型的值'阵<&协议下,P1,P2>>'到指定的类型'阵< P1>'


解决方案

您需要转换数组的元素,而不是数组本身。

  arrayTwo = arrayOne.map {$ 0作为P1}

或者像MartinR说,甚至有没有必要投的元素。

  arrayTwo = arrayOne.map {$ 0}

So I have two arrays

var arrayOne:Array<protocol<P1,P2>>
var arrayTwo:Array<P1>

Where P1 and P2 are protocols.

Question is how to make downcasting operation

arrayTwo = arrayOne as Array<P1>

What i get from Xcode is:

Cannot convert value of type 'Array<protocol<P1, P2>>' to specified type 'Array<P1>'

解决方案

You need to cast the elements of the array, not the array itself.

arrayTwo = arrayOne.map { $0 as P1 }

Or as MartinR stated, there is even no need to cast the element.

arrayTwo = arrayOne.map { $0 }

这篇关于向下铸造多协议阵列&LT;&协议下,P1,P2&GT;&GT;与Array&LT; P1&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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