adam-fowler
(Adam Fowler)
1
It appears CoreFoundation is not available on Swift for Windows.
I am doing the following to recognise if a NSNumber was initialized with a boolean and these functions are only available in CoreFoundation.
CFGetTypeID(number) == CFBooleanGetTypeID()
Is there either another method to identify an NSNumber initialized with a boolean, or will CoreFoundation be available for Windows soon?
tera
2
why do you need NSNumber instead of using swift native types if i may ask?
if you have it on windows you may try:
print(String(cString: number.objCType, encoding: .ascii)!)
but unfortunately this returns "c" for both Char and Boolean.
adam-fowler
(Adam Fowler)
3
I'm parsing dictionaries returned by JSONSerialization.jsonObject. I would much prefer not to have to deal with NSNumber at all but JSONSerialization code returns booleans as a NSNumber
tera
4
try this:
let dat = "{ \"some\" : true }".data(using: .utf8)!
let obj = try! JSONSerialization.jsonObject(with: dat, options: []) as! [String: Any]
let some = obj["some"]!
let someType = type(of: some)
let boolType = type(of: NSNumber(value: true))
let intType = type(of: NSNumber(value: 1))
print(someType)
assert(someType == boolType)
assert(someType != intType)
if some is NSNumber {
print("is NSNumber")
} else {
print("is not NSNumber")
}
1 Like
Jon_Shier
(Jon Shier)
7
We use this in Alamofire, and it has been guarantee stable across platforms:
extension NSNumber {
fileprivate var isBool: Bool {
// Use Obj-C type encoding to check whether the underlying type is a `Bool`, as it's guaranteed as part of
// swift-corelibs-foundation, per [this discussion on the Swift forums](https://forums.swift.org/t/alamofire-on-linux-possible-but-not-release-ready/34553/22).
String(cString: objCType) == "c"
}
}
2 Likes