是否有办法在Swift 2.1中实现这一点?
class Apple
{
}
class Fruit
{
let apples = [Apple]();
}
let fruit = Fruit();
let appleType: AnyClass = Apple.self;
let applesType: Any = fruit.apples.self.dynamicType;
let properties = Mirror(reflecting: fruit).children;
for property in properties
{
let magicalApples = property.value;
let array = Array<appleType>(); // creating array of Apple from type
let apples = magicalApples as! Array<appleType> // typecasting to array of Apple from type
let moreApples = magicalApples as! applesType // typecasting to [Apple] from type
let anyApples = magicalApples as! Array<AnyObject> // error SIGABRT, is this a bug?
}注释的目标抛出错误,“未声明类型的使用”。
我的目标是知道存储在** var**,中的 Type类型是否可以用作**Type
发布于 2015-12-26 06:15:59
这可以将apples附加到magicalApples中。
// Edit: NSObject added
class baseApple: NSObject
{
required override init()
{
}
}
class Apple: baseApple
{
}
// Edit: NSObject added
class Fruit: NSObject
{
var apples: [Apple] = [Apple]();
}
let fruit = Fruit();
let appleType: baseApple.Type = Apple.self;
let properties = Mirror(reflecting: fruit).children;
for property in properties
{
let magicalApples = property.value
var apples = magicalApples as! NSArray as Array<AnyObject> // first typecast to NSArray
apples.append(appleType.init()) // apples are now edible
// Edit
fruit.setValue(apples, forKey: "apples"); // apples supplied, of course I am assuming fruit object will be obtained dynamically.
}
fruit.apples.count; // output: 1上述方法适用于这种情况。不过,答案是“斯威夫特2.1是不可能的”
这对此进行了解释,谢谢@DevAndArtist的链接。
发布于 2015-12-25 19:58:22
不,你不能分配一个新的类型,因为它是一个let。
Cannot assign to immutable expression of type 'ClassName.Type'
-更新
let anyApples = magicalApples as! Array<AnyObject>应该是
let anyApples = magicalApples as! Array<Any>
-更新2
看看参考文献
https://stackoverflow.com/questions/34460875
复制相似问题