I'm getting an error when trying to check if an optional variable is set or not.
Error: Type CGPoint? does not confirm to protocol 'BooleanType.Protocol'
This is my code:
var point : CGPoint?
if (point) {
...
}
Isn't this how optional types in Swift are supposed to be used?
How should the if-comparison be written?
In Swift, a protocol defines a blueprint of methods or properties that can then be adopted by classes (or any other types). Here, Greet - name of the protocol. name - a gettable property.
In Swift, protocols contain multiple abstract members. Classes, structs and enums can conform to multiple protocols and the conformance relationship can be established retroactively.
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements.
The Swift Programming Language guide has this say on Class-Only Protocols: You can limit protocol adoption to class types (and not structures or enumerations) by adding the AnyObject protocol to a protocol's inheritance list.
Since beta 5, you should write point == nil
or point != nil
.
This change was made because of confusion when the value was an optional boolean. For example:
let maybe : Bool? = false
if maybe {
// executed because `maybe` is an optional having a value (false),
// not because it is true
}
You can also use the conditional assignment as before:
if let assignedPoint = point {
/* assignedPoint is now a CGPoint unwrapped from the optional */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With