Swift downcasting array of objects

综合编程 2018-06-24

import Foundation

class A: NSObject {

}

class B: A {

}

let array = [B(),B(),B(),B()]

array as? [A] //this does not works

B() as? A // this works

as?
is a conditional downcasting
operation (which can fail, and therefore returns an optional) – and you're trying to upcast
(which can never fail, and therefore you can do freely).

You therefore can just use as
in order to freely upcast the array – or rely on type inference, as Casey notes.

let arrayOfB = [B(),B(),B(),B()]

let arrayOfA = arrayOfB as [A] // cast of [B] to [A] via 'as'

let explicitArrayOfA : [A] = arrayOfB // cast of [B] to [A] via inference of explicit type 

func somethingThatExpectsA(a:[A]) {...}

somethingThatExpectsA(arrayOfB) // implicit conversion of [B] to [A]

Although the compiler's error of A is not a subtype of B
is certainly unhelpful in the context. A more suitable error (or maybe just a warning) could be 'as?' will always succeed in casting '[B]' to '[A]' – did you mean to use 'as'?
.

You should also note that for your example:

B() as? A // this works

You'll get a compiler warning saying Conditional cast from 'B' to 'A' always succeeds
. Although why
you get a compiler warning, rather than error for this – I can't say. I suspect it's due to the special way in which array casting happens.

Hello, buddy!

责编内容by:Hello, buddy! (源链)。感谢您的支持!

您可能感兴趣的

Swift4.0学习笔记(十)——步进器(UIStepper)... 1.定义控件 stepper = UIStepper() stepper.frame = CGRect(x: 0, y: 0, width: 100, he...
如何用 Swift 编写滑出式导航面板 原文: How to Create Your Own Slide-Out Navigation Panel in Swift ...
WWDC 2018 What’s New in Swift Recap In What’s New in Swift at WWDC 2018, Apple gave a quick overview of what’s n...
swift4 侧滑功能(使用DrawerController实现)... 直接上图 安装 类库开源地址:https://github.com/sascha/DrawerController 可惜的是,它已经...
Using child view controllers as plugins in Swift A very common problem when building apps for Apple's platforms is where to put ...