I've been trying to use the Autolayout Visual Format Language in Swift, using NSLayoutConstraint.constraintsWithVisualFormat
. Here's an example of some code that does nothing useful, but as far as I can tell should make the type checker happy:
let foo:[AnyObject]! = NSLayoutConstraint.constraintsWithVisualFormat(
format: "", options: 0, metrics: {}, views: {})
However, this triggers the compiler error:
"Cannot convert the expression's type '[AnyObject]!' to type 'String!'".
Before I assume this is a Radar-worthy bug, is there anything obvious I'm missing here? This happens even without the explicit casting of the variable name, or with other gratuitous downcasting using as
. I can't see any reason why the compiler would be expecting any part of this to resolve to a String!
.
this works for me with no error:
let bar:[AnyObject]! = NSLayoutConstraint.constraintsWithVisualFormat(
nil, options: NSLayoutFormatOptions(0), metrics: nil, views: nil)
the line above may not be compiled since the 1st and 4th parameters cannot be optionals anymore.
syntactically those have to be set, like e.g. this:
let bar:[AnyObject] = NSLayoutConstraint.constraintsWithVisualFormat("", options: NSLayoutFormatOptions(0), metrics: nil, views: ["": self.view])
(for Xcode 7, Swift 2.0)
the valid syntax now requests the parameters's name as well, like:
NSLayoutFormatOptions(rawValue: 0)
NOTE: this line of code shows the correct syntax only, the parameters itself won't guarantee the constraint will be correct or even valid!