arraysswiftnsmutablearray

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


Solution

  • 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
    
    }