Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Init has been renamed to init(describing) error in Swift 3

Tags:

swift

swift3

This code works fine in Swift 2:

guard let userData = responseData["UserProfile"] as? [String : AnyObject] else { return }

var userProfileFieldsDict = [String: String]()
if let profileUsername = userData["Username"] as? NSString {
  userProfileFieldsDict["username"] = String(profileUsername)
}
if let profileReputationpoints = userData["ReputationPoints"] as? NSNumber {
  userProfileFieldsDict["reputation"] = String(profileReputationpoints)
}

But, in Swift 3 it throws an error on userProfileFieldsDict["reputation"] saying

init has been renamed to init(describing:)

My question is why does it trigger on that line and not on the userProfileFieldsDict["username"] assignment line, and how to go about fixing it? I'm assuming it's because I'm casting a NSNumber to a String, but I can't really understand why that matters.

like image 543
ardevd Avatar asked Oct 07 '16 17:10

ardevd


2 Answers

NSNumber is a very generic class. It can be anything from a bool to a long to even a char. So the compiler is really not sure of the exact data type hence it's not able to call the right String constructor.

Instead use the String(describing: ) constructor as shown below

userProfileFieldsDict["reputation"] = String(describing: profileReputationpoints)

Here's more info about it.

like image 144
eshirima Avatar answered Jan 02 '23 16:01

eshirima


You need to drop your use of Objective-C types. This was always a bad habit, and now the chickens have come home to roost. Don't cast to NSString and NSNumber. Cast to String and to the actual numeric type. Example:

if let profileUsername = userData["Username"] as? String {
    userProfileFieldsDict["username"] = profileUsername
}
if let profileReputationpoints = userData["ReputationPoints"] as? Int { // or whatever
    userProfileFieldsDict["reputation"] = String(profileReputationpoints)
}
like image 30
matt Avatar answered Jan 02 '23 17:01

matt