Priyanka
Priyanka

Reputation: 513

Cannot convert value of type 'Any' to specified type in swift

I have created one array like below

var childControllers = NSArray()
childControllers = NSArray(objects: OBDPage1, OBDPage2, OBDPage3, OBDPage4)
self.loadScrollView(page: 0)// calling method

now I want to use array object like below

func loadScrollView(page: Int){ // method
    if page >= childControllers.count {
        return
    }
    // replace the placeholder if necessary
    let controller: OBDPage1ViewController? = childControllers[page]
}

but I am getting below error

Swift-CarAssist/Swift-CarAssist/OBDCarMonitorDeatilViewController.swift:90:67: Cannot convert value of type 'Any' to specified type 'OBDPage1ViewController?'

can any one tell me where I am going wrong as I am new to swift.

Thanks in advance. Priyanka

Upvotes: 3

Views: 8398

Answers (2)

Ashley Mills
Ashley Mills

Reputation: 53231

Working in Swift you should use Swift Array rather than NSArray

var childControllers = [UIViewController]()
childControllers = [OBDPage1,OBDPage2,OBDPage3,OBDPage4]
self.loadScrollView(page: 0)// calling method

then

func loadScrollView(page: Int){ // method

    if page >= childControllers.count {
        return
    }

    // replace the placeholder if necessary
    let controller = childControllers[page] as? OBDPage1ViewController

}

Upvotes: 5

Benjamin Lowry
Benjamin Lowry

Reputation: 3799

Try this:

let controller = childControllers[page] as! OBDPage1ViewController

You have to explicitly cast the array value as an OBDPage1ViewController, otherwise it is just of type Any.

Edit:

To be more safe, it is recommended that you perform this using if-let conditional binding.

if let controller = childControllers[page] as? OBDPage1ViewController {
    //do something    
}

Upvotes: 2

Related Questions