Swift AnyObject is not convertible to String/Int
In Swift, String
and Int
are not objects. This is why you are getting the error message. You need to cast to NSString
and NSNumber
which are objects. Once you have these, they are assignable to variables of the type String
and Int
.
I recommend the following syntax:
if let id = reminderJSON["id"] as? NSNumber {
// If we get here, we know "id" exists in the dictionary, and we know that we
// got the type right.
self.id = id
}
if let receiver = reminderJSON["send_reminder_to"] as? NSString {
// If we get here, we know "send_reminder_to" exists in the dictionary, and we
// know we got the type right.
self.receiver = receiver
}
AnyObject is not convertible to String
name["name"]
will return a value of type AnyObject?
. It is optional because dictionary
look ups always return optionals since the key might be invalid. You should conditionally
cast it to type NSString
which is an object type and then use optional binding (if let
)
to bind that to a variable in the case where the loop up does not return nil
:
if let myname = name["name"] as? NSString {
cell.textLabel?.text = myname
}
or if you want to use an empty string if "name" is not a valid key, the nil coalescing operator ??
comes in handy:
cell.textLabel?.text = (name["name"] as? NSString) ?? ""
Swift 2: AnyObject? is not convertible to NSString
try this ...
if let username = prefs.valueForKey("USERNAME") as? String{
self.usernameLabel.text = username
}
or if you want to use NSString .. (Just an option)
if let username = prefs.valueForKey("USERNAME") as? NSString{
self.usernameLabel.text = username
}
Any' is not convertible to '[[String : Any]]'
why are you using AnyHashable
??
Try this:
let jsonArray: Any? = nil
do {
jsonArray = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [Any]
if jsonArray != nil {
if let resp = jsonArray as? [[AnyHashable : Any]]{
//your result should be here inside resp, which is an array of dictionary of key-val type `AnyHashable : Any`, although you could just use String value for the key, making your format from [[AnyHashable : Any]] to [[String : Any]]
}
}
catch {
let description = NSLocalizedString("Could not analyze earthquake data", comment: "Failed to unpack JSON")
print(description)
return
}
Swift AnyObject is not convertible to String/Int
In Swift, String
and Int
are not objects. This is why you are getting the error message. You need to cast to NSString
and NSNumber
which are objects. Once you have these, they are assignable to variables of the type String
and Int
.
I recommend the following syntax:
if let id = reminderJSON["id"] as? NSNumber {
// If we get here, we know "id" exists in the dictionary, and we know that we
// got the type right.
self.id = id
}
if let receiver = reminderJSON["send_reminder_to"] as? NSString {
// If we get here, we know "send_reminder_to" exists in the dictionary, and we
// know we got the type right.
self.receiver = receiver
}
AnyObject is not convertible to 'String'
My understanding is that jsonparser.objectWithString(answer)
is supposed to return an array, basing on the name of the variable it is assigned to.
If it's an array of heterogeneous types, you can attempt a cast to NSArray
:
if let answerArray = jsonparser.objectWithString(answer) as? NSArray {
...
}
If the array is supposed to contain objects of the same type (let's say Int
) instead, then you can try a cast to a swift array:
if let answerArray = jsonparser.objectWithString(answer) as? [Int] {
...
}
Note that a non-optional variable can never be nil
- and you have declared answerArray
as a non-optional.
If you want to check for NSNull
, I suggest reading this question and related answer.
AnyObject (from JSONObjectWithData) is not convertible to [String : Any]
After experimenting a bit in Playground, the code below seems to work. Note that Any
does not work, while AnyObject
seems to work as expected.
let jsonString = "{\"name\":\"John\", \"age\":23}"
let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
let json = NSJSONSerialization.JSONObjectWithData(jsonData,
options: NSJSONReadingOptions.MutableContainers, error: nil) as [String:AnyObject]
// ["name": "John", "age": __NSCFNumber]
let name = json["name"] as AnyObject! as String // "John"
let age = json["age"] as AnyObject! as Int // 23
Any type in swift and conversion to Int
In a strongly typed language it is important to get your types right as early as possible. Otherwise you'll end up fighting the type system at every turn.
In your case, the placeholder, as you've described, needs to be Any
because it is carrying arbitrary data - but n
is an Int
and should be declared as such.
Your code should have this feel:
func processPlaceholder (placeHolder: Any) {
if let n = placeHolder as? Int {
n = n * 4
// ...
}
else if let s = placeHolder as? String {
s = s + "Four"
// ....
}
// ...
}
Related Topics
Class-Only Generic Constraints in Swift
Correct Handling/Cleanup/Etc of Cadisplaylink in Swift Custom Animation
In Swift, Does Resetting the Property Inside Didset Trigger Another Didset
Clearing Uiwebview's Cache in Swift
What Is the Property Block Declaration Equivalent in Swift of the Following Block Property
Unsafemutablepointer in Swift as Replacement for Properly Sized C Array in Obj-C
Understanding the Userdefaults Register Method
App Crashes When Playing Audio on iOS13.1
Fbsdkapplicationdelegate Application Openurl:Sourceapplication:Annotation Deprecated
How to Code Initwithcoder in Swift
Reversing the Order of a String Value
How Is a Return Value of Anyobject! Different from Anyobject
How to Succinctly Get the First 5 Characters of a String in Swift
How to List Swift Types That Conform to Protocol Using Reflection