BadmintonCat
BadmintonCat

Reputation: 9586

Cannot convert value of type '() -> _' to specified type 'Bool'

Why does this code gives me the above compile time error?

var results = [[String:Bool]]()

var isSuccessful:Bool =
{
    for (index, element) in results.enumerated()
    {
        if element.values.contains(false) { return false }
    }
    return true
}

Upvotes: 1

Views: 2587

Answers (2)

CZ54
CZ54

Reputation: 5588

Just remove the = sign

var isSuccessful:Bool {
     get {
            for (index, element) in results.enumerated()
            {
                if element.values.contains(false) { return false }
            }
            return true
         }
    }

If you use the = sign, you want to 'assign' a value to your variable. This is a common mistake to lazy var initialization

lazy var isSuccessful:Bool =  {
            for (index, element) in results.enumerated()
            {
                if element.values.contains(false) { return false }
            }
            return true
    }()

This syntax will process the block when you are getting the variable the first time.

Upvotes: 4

Hexfire
Hexfire

Reputation: 6058

There are two cases.

1) Computed property:

var isSuccessful:Bool
{
    for (index, element) in results.enumerated()
    {
        if element.values.contains(false) { return false }
    }
    return true
}

2) Lazy variable:

lazy var isSuccessful : Bool = 
{
    for (index, element) in results.enumerated()
    {
        if element.values.contains(false) { return false }
    }
    return true
}()

Both are correct. Choose the one you need.

Semantically:

  • computed property is evaluated on every access.
  • lazy variable is evaluated just once, on first access, but not on startup.

Upvotes: 2

Related Questions