有没有办法在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?
}
评论的目标会引发错误,&#34;使用未声明的类型&#34;。
我的目标是知道存储在appleType
中的var
类型是否可以用作Type
答案 0 :(得分:0)
不,你不能指定一个新类型,因为它是一个let
Cannot assign to immutable expression of type 'ClassName.Type'
- 更新 -
let anyApples = magicalApples as! Array<AnyObject>
应该是
let anyApples = magicalApples as! Array<Any>
?
- 更新2 -
答案 1 :(得分:0)
这可以将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
以上适用于这种情况。 尽管如此,答案是不可能使用Swift 2.1&#39;
This解释了这一点,感谢@DevAndArtist提供的链接。