gpt4 book ai didi

Swift AnyObject - 将协议(protocol)数组向下转换为 [AnyObject]

转载 作者:搜寻专家 更新时间:2023-10-31 22:21:08 29 4
gpt4 key购买 nike

如何将协议(protocol)实例数组向下转换为 AnyObject?我在下面的代码示例中尝试了一些更合理的想法。

protocol Nameable : class {
var name: String { get }
}

class Person: Nameable {
var name: String

init(name: String)
{
self.name = name
}
}

class Example {

func setArray(array: [AnyObject]?, forKey: String)
{
print("hello world")
}
}

var personOne = Person(name: "Evan")
var personTwo = Person(name: "Brian")

var array: [ Nameable ] = [ personOne, personTwo ]

var anotherArray = array.map({ $0 as AnyObject }) // OMG gross!
var yetAnotherArray = array as [ AnyObject ] // Nope.
var evenYetAnotherArray = array as? [ AnyObject ] // Nope.
var omgThisIsAnArray = Array<AnyObject>(array) // Ha ha, srsly. Nope.

var myExample = Example()
myExample.setArray(anotherArray, forKey: "Named")

就其值(value)而言,setArray(_ anArray: [AnyObject]?, forKey aKey: String) 方法签名来自 Apple 的 NSUbiquitousKeyValueStore 类,所以我不能真正重新设计它是类型安全的。

最佳答案

它并不完美,但如果协议(protocol)和类都是@objc(以及类的子类NSObject),它就可以工作:

@objc protocol Nameable: class {
var name: String { get }
}

@objc class Person: NSObject, Nameable {
var name: String
init(name: String) {
self.name = name
}
}

...

var array: [Nameable] = [personOne, personTwo]
let array2 = array as [AnyObject] // ✓

关于Swift AnyObject - 将协议(protocol)数组向下转换为 [AnyObject],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36636615/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com