Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanly converting an Objective-C Boolean to a Swift Bool?

Is there an easy way to do this that I'm missing? Right now I'm doing this like so:

let doesConformNumber: NSNumber = NSNumber(unsignedChar: UTTypeConformsTo(utiCF, typeCF))
if doesConformNumber.boolValue {
    return true
}

If I try to do a simple cast like so:

let testBool: Bool = UTTypeConformsTo(utiCF, typeCF)

I get the error 'Boolean' is not convertible to 'Bool'

Anyone have a cleaner way of doing this conversion?

like image 403
arcticmatt Avatar asked Aug 29 '14 03:08

arcticmatt


People also ask

Can BOOL be nil Objective-C?

By default, a bool value is set to 0 in Objective-C, so you don't need to check if your bool value is nil anytime.

How do you print a boolean in Objective-C?

There is no format specifier to print boolean type using NSLog. One way to print boolean value is to convert it to a string. Another way to print boolean value is to cast it to integer, achieving a binary output (1=yes, 0=no).

Is boolean a swift?

Swift uses only simple Boolean values in conditional contexts to help avoid accidental programming errors and to help maintain the clarity of each control statement. Unlike in other programming languages, in Swift, integers and strings cannot be used where a Boolean value is required.

What is boolean in Objective-C?

A boolean is binary value expressed in Objective-C as the primitive type BOOL which can hold either YES or NO (true or false) values. Their primary use in programming is in decision making.


1 Answers

UTTypeConformsTo() returns a Boolean, which is a type alias for Int8 and not directly convertible to Bool. The simplest way would be

let testBool : Bool = UTTypeConformsTo(utiCF, typeCF) != 0

where the type annotation is actually not necessary:

let testBool = UTTypeConformsTo(utiCF, typeCF) != 0
like image 131
Martin R Avatar answered Oct 06 '22 22:10

Martin R