Trying to convert NSDate to Date and getting warning - ios

I am getting the following warning
Forced cast from 'NSDate?' to 'Date' only unwraps and bridges; did you
mean to use '!' with 'as'?
on the following line of code:
pickDate.date = item?.date as! Date
where pickDate is a UIDatePicker. The code works and if I try to follow the recommended fixes, they loop with other warnings or errors that are no better.
Any suggestions?

Using Swift 3.x (Xcode 8.3.3) I was able to get rid of the warning with:
pickDate.date = item.date! as Date
But this assumes "item" is not an optional anymore (on my code I can if-let it).

if let model = item, item?.date != nil{
pickDate.date = model.date
}

item is an Entity does not provide enough info (better include the definition of the entity), but according to the message, item?.data is of type NSDate? (aka Optional<NSData>). You can convert NSDate to Date with as-casting, as well as NSDate? to Date?:
(You usually do not use as! or as? when converting between NSDate and Date.)
if let theDate = item?.date as Date? {
pickDate.date = theDate
} else {
//Generally, silently ignoring unexpected value would be a bad habit.
print("`item?.date` is nil")
}

item maybe nil. then item?.data maybe nil.
try this:
pickDate.date = item!.date as! Date
or
pickDate.date = (item?.date)! as Date

Related

Sort coredata Array based on a NSSet attribute

I have a coredata Array that has one to many relationship where one Account could have many Logs (Account<->>Logs). My objective is to sort the Account array, based on a child attribute value which is a date inside my Log. So far what i have tried and fail as bellow.
func sortBy(types:[String],clonedAccountArray:[Account]) {
let dateFormater1 = DateFormatter()
dateFormater1.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let arr = clonedAccountArray.sorted { (acc1, acc2) -> Bool in
(dateFormater1.date(from: (acc1.logs?.allObjects as! [SalesLogs]).last?.created_date ?? "")?.compare(dateFormater1.date(from: (acc2.logs?.allObjects as! [SalesLogs]).last?.created_date ?? "")!) == .none)
}
}
Hence this gives an exception saying "Unexpectedly found nil while unwrapping an Optional value". However i believe my sorting code is wrong. Any insights would much appreciate to find the erro

How to fix 'Cannot assign value of type 'NSDate' to type 'Date?'

I am a beginner with swift and I'm trying to complete my first app.
While I was typing the code, it showed me this:
Cannot assign value of type 'NSDate' to type 'Date?
at
newBirthday.birthdate = birthdate as NSDate
I tried writing statements for making that line of code work but it wouldn't. Every time now I am running it, I would get 6 errors.
let newBirthday = Birthday(context: context)
newBirthday.firstName = firstName
newBirthday.lastName = lastName
newBirthday.birthdayGift = birthdayGift
newBirthday.birthdate = birthdate as NSDate
newBirthday.birthdayID = UUID().uuidString
Starting with Swift 3, it no longer used Objective-c libraries NS
So if use Swift 3.0 or greater, then remove NS Prefix
In your case Birthday Object variable 'birthdate' is Date type not NSDate
if you can not assign NSDate in the Date object, for assign NSDate in Date you have cast first in Date.
newBirthday.birthdate = birthdate

Get String value from an optional in Swift 4

I am new to Swift and am trying to compare my Error description name with different String constants to show the user different results, based on the error.
I am using:
let errorName = errors.first?["name"].debugDescription
The value of errorName comes as "Optional(AlreadyActiveUser)" and when i compare this to my constant string "AlreadyActiveUser", i get false.
I have tried many things, but i am not able to get the value of the string inside the optional.
Someone, please help.
You can use optional binding in this case...
guard let errorName = errors.first?["name"].debugDescription as? String {
print("value is not present...")
return
}
print(errorName)
//here you can compare errorName == "AlreadyActiveUser"
you can use this
if let errorName = errors.first?["name"] as? String {
print(errorName)
//here you can compare errorName == "AlreadyActiveUser"
}
else
{
print("value is not present...")
}
try let errorName = errors.first!["name"].debugDescription
Notes that I forced wrapping first with ! instead of ?.

iOS Swift: Could not cast value type '__NSCFNumber' to 'NSString'

I am retrieving a number value from my Firebase database (JSON db) and then displaying this number into a textField, although I get this error when I try to display it.
Could not cast value type '__NSCFNumber' to 'NSString'
How can I properly convert the retrieved value to a String, taking into consideration that this value maybe change between a String and a Number when I retrieve it.
Here is my code:
let quantity = child.childSnapshot(forPath: "quantity").value // Get value from Firebase
// Check if the quantity exists, then add to object as string.
if (!(quantity is NSNull) && ((quantity as! String) != "")) {
newDetail.setQuantity(quantity: quantity as! String)
}
The error is saying that your quantity is Number and you cannot directly convert number to String, try like this.
newDetail.setQuantity(quantity: "\(quantity)")
Or
if let quantity = child.childSnapshot(forPath: "quantity").value as? NSNumber {
newDetail.setQuantity(quantity: quantity.stringValue)
}
else if let quantity = child.childSnapshot(forPath: "quantity").value as? String {
newDetail.setQuantity(quantity: quantity)
}
Or With Single if statement
if let quantity = child.childSnapshot(forPath: "quantity").value,
(num is NSNumber || num is String) {
newDetail.setQuantity(quantity: "\(quantity))
}
Using second and third option there is no need to check for nil.
Swift 4:
let rollNumber:String = String(format: "%#", rollNumberWhichIsANumber as! CVarArg)
You may convert your NSNumber value to string like this too, its more traditional and basic approach to format a string
newDetail.setQuantity(String(format: "%#", quantity))
Swift 4.
newDetail.setQuantity(String(describing: rollNumberWhichIsANumber))
In swift 4.1 and Xcode 9.4.1
newDetail.setQuantity(quantity: "(quantity)")
We can convert to string like this "\(quantity)"
let session_id : Int32 = (jsonObject.value(forKey: "id") as! NSNumber).int32Value
Swift 5:
I manage to fix it buy using .description when interpolating the UserDefaults value into a label converting from Int to String.
working code
highScoreLabel?.text = "HiScore: \(hiScoreValue.description)"
old code
highScoreLabel?.text = "HiScore: \(String(describing: hiScoreValue))"

How do I get Parse data as a String out of PFUser?

I am currently trying to get a value called "loot" out of the current user. I need the value as a String, but Swift is being stubborn and says it "cannot convert Anyobject to String". The Parse documentation for iOS says to use something like:
let score = gameScore["score"] as String
and so, I try this :
let lootAmount = user["loot"] as String
BTW 'user' is referring to the current user. When I try that, it gives error saying it's not convertible. I tried placing '!'s and '?'s wherever Xcode suggested, but it just crashed the app with no error.
So, how do I get the user value called "loot" as a String?
Loot is an NSNumber not an NSString or String.
You could convert it to a String like this:
if let loot = user["loot"] as? NSNumber {
let lootString = "\(loot)"
}
If you're not sure of an object's type, you can ask it using dynamicType:
print(user["loot"]!.dynamicType)
//prints `__NSCFNumber.Type`
You may need to downcast AnyObject. Try this: let lootAmount = user["loot"] as? String or unwrap your optional user if you haven't done so:
let currentUser = PFUser.currentUser()
if let user = currentUser {
let lootAmount = user["loot"] as String
}

Resources