Prabhat Pankaj
Prabhat Pankaj

Reputation: 192

How to type cast in swift language

Please let me know how to type cast in Swift language.

[(FXImageView *)view setImageWithContentsOfURL:[items objectAtIndex:index]];

Upvotes: 1

Views: 182

Answers (2)

mustafa
mustafa

Reputation: 15464

There is three keyword for typecasting in swift.

First one is as. It is used for the situations like casting from subclass to superclass. If you are using as for typecasting it is checked at compile time to guarantee casting is never failed. So its use pretty limited. Here is a sample:

class SuperClass {}

class SubClass: SuperClass {}

let a = SubClass()
let b = a as SuperClass

The second one is as?. It works basically like this. If casting is succeeded it returns an Optional.Some<YourType>(yourObject) and if it is failed it returns Optional<YourType>.None (etc nil). Here is a sample:

let someValue = 20
if let castedValue = someValue as? String {
    print("casting successfull. The value is \(castedValue)")
} else {
    print("casting failed")
}

Here obviously casting from Int to String will fail and else part will be executed.

The third one is as!. Its use case is similar to as?. If casting is successful you will get implicitly unwrapped optional and if it is failed your program will crash (as with other operations includes !.). Here is a sample use

let someValue = 20
let castedValue = someValue as! String

You should only use this one if you are sure the casting operation will always be successful. For your code I would write it like this

if let imageView = view as? FXImageView {
    imageView.setImageWithContentsOfURL(items[index])
} else {
    // handle the fail part
}

Or with map method on Optional

(view as? FXImageView).map { $0.setImageWithContentsOfURL(items[index]) }

Upvotes: 0

LinusG.
LinusG.

Reputation: 28982

That code should translate to something like

let view = FXImageView(imageWithContensOfURL(items[index]))

Hope that helps :)

Upvotes: 1

Related Questions