2

Is there a way to achieve this in 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?
}

Commented objectives throws error, "Use of undeclared type".

My objective is to know if appleType, type stored in a var, can be used as a Type

parveen
  • 1,939
  • 1
  • 17
  • 33

2 Answers2

0

No, you can't assign a new type, because it's a let.
Cannot assign to immutable expression of type 'ClassName.Type'

-- Update --

let anyApples = magicalApples as! Array<AnyObject> should be
let anyApples = magicalApples as! Array<Any>?

-- Update 2 --

Look at the references

  • I don't want to assign, I want to typecast. – parveen Dec 26 '15 at 06:13
  • You sad "My objective is to know if appleType, type stored in a var, can be used as a Type".. However now I'm editing the answer. –  Dec 26 '15 at 13:56
  • exactly, "can be used as a **Type** for *typecasting*". Anyways your code gives error, refer to my answer. – parveen Dec 26 '15 at 15:06
0

This works to append apples to 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

Above works for this situation. Although, the answer is 'it's not possible with Swift 2.1'

This explains it, thanks @DevAndArtist for the link.

Community
  • 1
  • 1
parveen
  • 1,939
  • 1
  • 17
  • 33