var dict: [String: Any] = ["key" : "value"]
let a = dict["key"]
print( "dict[key] = (type(of: a))")
This prints: dict[key] = Optional
Not really wrong; but not what I want.
I want to get a not-optional "String"
How can this be done?
Gerriet.
var dict: [String: Any] = ["key" : "value"]
let a = dict["key"]
print( "dict[key] = (type(of: a))")
This prints: dict[key] = Optional
Not really wrong; but not what I want.
I want to get a not-optional "String"
How can this be done?
Gerriet.
You can safely unwrap the value and then pass it to type(of:)
. Or, you can use Mirror
:
let mirror = Mirror(reflecting: a)
for child in mirror.children {
print(type(of: child.value)) // This will print 'String'
}
Very helpful!
This now works:
var dict: [String: Any] = ["key" : 12.7]
let a = dict["key"]
let aType = a == nil ? "nil" : "(type(of: a!))"
print( "dict[key] = (aType)") // dict[key] = Double
Thanks a lot!
Gerriet.
This toy example works fine.
But in in my real app I get:
… received: __NSCFString
Is there some way to convert “__NSCFString” to “String” (or at least “NSString”) ?
Gerriet.
Can you post your code?
suyashsrijan
June 6
Can you post your code?
No, this would be too much.
I receive a dictionary [String: Any] via NWNetwork (called just Network in Swift).
Then I do:
let thing = dictionary[“some key”]
and try to print the class name of “thing”. And want something simple like: nil, Double, Data, String, etc.
You can try casting it to String maybe? For example: theClass as? String
?
suyashsrijan
June 6
You can try casting it to String maybe? For example: theClass as? String?
Sure. I can do
if let string = thing as? String
className = “String”
else if let data = thing as? Data
…
But then I might receive some __NSDatePrivateSubclass
Ok, I then add
else if let date = thing as? Date
..
and so on.
This is a never ending process.
I was hoping for something general to convert these private subclasses into their umbrella class, or, even better, into their Swift equivalent.
Gerriet.
I don't think you can automatically do it - you would have to cast it manually.
What are you trying to achieve here?
suyashsrijan
June 6
I don't think you can automatically do it - you would have to cast it manually.
I feared it would be like this.
What are you trying to achieve here?
Just to print a user-friendly description of the dictionary received over the Network framework.
This has been discussed: