首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >来自AnyClass或dynamicType的数组

来自AnyClass或dynamicType的数组
EN

Stack Overflow用户
提问于 2015-12-25 07:23:28
回答 2查看 883关注 0票数 2

是否有办法在Swift 2.1中实现这一点?

代码语言:javascript
复制
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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-12-26 06:15:59

这可以将apples附加到magicalApples中。

代码语言:javascript
复制
// 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的链接。

票数 0
EN

Stack Overflow用户

发布于 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

看看参考文献

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34460875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档