Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Type does not confirm to protocol 'BooleanType.Protocol'

Tags:

swift

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?

like image 689
Anton Avatar asked Aug 06 '14 08:08

Anton


People also ask

What is the type of protocol in Swift?

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.

Can struct conform to protocol Swift?

In Swift, protocols contain multiple abstract members. Classes, structs and enums can conform to multiple protocols and the conformance relationship can be established retroactively.

How do protocols work in Swift?

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.

What is class only protocol Swift?

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.


1 Answers

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 */ 
}
like image 173
Jesper Avatar answered Sep 22 '22 04:09

Jesper