Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign value of type UnsafeMutablePointer ObjCBool in Swift

I'm unfamiliar with Objective C.

I'm using a private framework and need to be able to change one of the properties from within my Swift code.

The property is declared in Objective C this way:

@property (nonatomic, assign) BOOL *isSSNField;

in swift I am trying to change the value of the property this way:

myClass.isSSNField = true

I am getting this error

Cannot assign a value of type 'Bool' to a value of type 'UnsafeMutablePointer<ObjcBool>'

I'm not sure where to go from here, or why I'm getting this error at all

like image 665
YichenBman Avatar asked May 19 '15 18:05

YichenBman


3 Answers

Update for Swift 5.1

For pointer types Swift provides pointee property,

Documentation for v5.1 says it is used for accessing instance referenced by this pointer

You can easily set the pointee field

myClass.isSSNField.pointee = false

And this is same for all pointer types and conversions. If you want to check the value of an Objective C BOOL* You can easily

if myClass.isSSNField.pointee.boolValue
like image 182
accfews Avatar answered Nov 19 '22 01:11

accfews


I've never seen anything like the situation you describe, and personally I'm tempted to say the situation doesn't exist; I have never seen a BOOL* property or ivar in Objective-C in my life (and I'm darned old, believe me). However, if you insist: I haven't tested this, but I think you could say something like this:

var ok = UnsafeMutablePointer<ObjCBool>.alloc(1)
ok[0] = false // or true
let val = ok
myClass.isSSNField = val

However, although I think that will compile, I'm rather unclear on what the implications of doing it would be. It could cause the universe to collapse to a black hole, so be careful.

like image 21
matt Avatar answered Nov 19 '22 01:11

matt


BOOL* in Objective-C is a pointer of Bool.
Use UnsafeMutablePointer in Swift.

var isSSNField: ObjCBool = true
myClass.isSSNField = &isSSNField

Then fix it.

Just like the isDirectory parameter in function:

func fileExists(atPath path: String, isDirectory:UnsafeMutablePointer<ObjCBool>?) -> Bool

You can use the code:

var isDirectory:ObjCBool = true
var isFileExists = FileManager.default.fileExists(atPath: <#YourPath#>, isDirectory: &isDirectory)
like image 16
TanJunHao Avatar answered Nov 19 '22 02:11

TanJunHao