Can I do dynamic casting?


(Zhao Xin) #1

Is that possible to do dynamic casting?

My code:

import Foundation

let array = [1,2,3,4,5]

let dictionary:[String:Any] = ["numbers":array]

if let value = dictionary["numbers"] {

    let type = type(of: value)

    print(type) // Array<Int>

    let numbers = value as! Array<Int> // [1, 2, 3, 4, 5]

    //let numbers2 = value as! type // error: use of undeclared type 'type'

}

As you can see, the dynamic casting leads an error. Is there a way to do
this? Thanks.

Zhaoxin


(Johan Segerfeldt) #2

Zhaoxin,

You are trying to cast to a type which is defined by a variable at runtime.
Casting with `as` is done at compile-time. The variable has no defined value at this time.

The compiler cannot infer what the value of a variable is going to be.
It can only infer types by static analysis.

Regards
Johan

···

Is that possible to do dynamic casting?

My code:

importFoundation

letarray = [1,2,3,4,5]

letdictionary:[String:Any] = ["numbers":array]

ifletvalue =dictionary["numbers"] {

lettype = type(of: value)

print(type)// Array<Int>

letnumbers = valueas!Array<Int>// [1, 2, 3, 4, 5]

//let numbers2 = value as! type // error: use of undeclared type 'type'

}

As you can see, the dynamic casting leads an error. Is there a way to do this? Thanks.

Zhaoxin


(Zhao Xin) #3

Thanks, Jordan. Is there any other way to do that?

Zhaoxin

···

On Thu, Aug 25, 2016 at 6:40 PM, Johan Segerfeldt <Johan.Segerfeldt@fiwe.se> wrote:

Zhaoxin,

You are trying to cast to a type which is defined by a variable at runtime.
Casting with `as` is done at compile-time. The variable has no defined
value at this time.

The compiler cannot infer what the value of a variable is going to be.
It can only infer types by static analysis.

Regards
Johan

> Is that possible to do dynamic casting?
>
> My code:
>
> >
> > importFoundation
> >
> >
> >
> >
> >
> >
> >
> >
> > letarray = [1,2,3,4,5]
> >
> >
> >
> > letdictionary:[String:Any] = ["numbers":array]
> >
> >
> >
> >
> >
> >
> >
> >
> > ifletvalue =dictionary["numbers"] {
> >
> >
> >
> > lettype = type(of: value)
> >
> >
> >
> > print(type)// Array<Int>
> >
> >
> >
> > letnumbers = valueas!Array<Int>// [1, 2, 3, 4, 5]
> >
> >
> >
> > //let numbers2 = value as! type // error: use of undeclared type 'type'
> >
> >
> >
> > }
> >
> >
> As you can see, the dynamic casting leads an error. Is there a way to do
this? Thanks.
>
>
>
>
>
>
> Zhaoxin
>
>
>
>
>
>


(Jens Alfke) #4

It would be best if you explained what you’re trying to do with such a feature; then we can describe how to do it in Swift.

—Jens

···

On Aug 25, 2016, at 5:38 AM, Zhao Xin via swift-users <swift-users@swift.org> wrote:

Thanks, Jordan. Is there any other way to do that?