4

The code shown below:

Int(false) // = 1, it's okay

//but when I try this
let emptyString = true //or let emptyString : Bool = true
Int(emptyString) //error - Cannot invoke initializer with an argument list of type '(Bool)'

Can anyone explain this fact? It's confusing. What happens inside?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
G. Veronika
  • 232
  • 2
  • 11

4 Answers4

5

To find out what is going on with Int(false), change it to:

Int.init(false)

and then option-click on init. You will see that it is calling this initializer:

init(_ number: NSNumber)

Since false is a valid NSNumber and NSNumber conforms to the protocol ExpressibleByBooleanLiteral, Swift finds this initializer.

So why doesn't this work?:

let emptyString = false
Int(emptyString)

Because now you are passing a Bool typed variable and Int doesn't have an initializer that takes a Bool.

In Swift 2 this would have worked because Bool was automatically bridged to NSNumber, but that has been removed.

You can force it like this:

import Foundation // or import UIKit or import Cocoa
Int(emtpyString as NSNumber)

This only works if Foundation is imported. In Pure Swift there is no NSNumber, of course.

vacawama
  • 150,663
  • 30
  • 266
  • 294
0

Try this

let intValue = emptyString ? 1 : 0

Update

You want to use Int(), use this

Int(NSNumber(value:emptyString))
Dileep
  • 2,399
  • 4
  • 26
  • 39
0

Int doesn't have initialiser with Bool as argument.

Artem Novichkov
  • 2,356
  • 2
  • 24
  • 34
0

Are you sure you do not have something like this somewhere in your codebase:

extension Int : ExpressibleByBooleanLiteral {
    public init(booleanLiteral: BooleanLiteralType) {
        self = booleanLiteral ? 1 : 0
    }
}

Because otherwise, the line like let foo = Int(false) should not compile.

0x416e746f6e
  • 9,872
  • 5
  • 40
  • 68