Adamski
Adamski

Reputation: 3675

"Type of expression is ambiguous without more context" on array initialisation in Swift 2

I'm getting the error "Type of expression is ambiguous without more context" when trying to initialise an array of UIViewControllers.

The relevant parts of my class look like this:

// ScaleViewController inherits from UIViewController
var scaleViewController: ScaleViewController? 

func myFunc(sender: AnyObject) {
    //...
    let masterVC: UIViewController = self.splitViewController!.viewControllers[0] as UIViewController
    let viewControllers = [masterVC, self.scaleViewController] 
    // Above line gives "Type of expression is ambiguous without more context" at "masterVC"
    self.splitViewController!.viewControllers = viewControllers
    //...
}

Upvotes: 0

Views: 1301

Answers (2)

Vladimir Kofman
Vladimir Kofman

Reputation: 1993

In Swift, arrays are homogenous by default, meaning that all members of array should be of the same type. In your example, masterVC is of type UIViewController, while self.scaleViewController is of type UIViewController? (Optional UIViewController, which is different from UIViewController).

One of the options in your case is to define explicitly type for viewControllers array:

let viewControllers:[UIViewController?] = [masterVC, self.scaleViewController]

Upvotes: 2

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

Try this:

let masterVC: UIViewController = self.splitViewController!.viewControllers[0] as UIViewController
guard let scalView = scaleViewController else { return }
let viewControllers = [masterVC, scalView]

Upvotes: 2

Related Questions