(Swift)Help me with 'DocumentReference' initialize error problem [duplicate] - ios

This question already has answers here:
Conditional Binding: if let error – Initializer for conditional binding must have Optional type
(8 answers)
Closed 2 years ago.
let saveDocument = Firestore.firestore()
let docId = UserDefaults.standard.object(forKey: "docId") as! String
print(docId)
if let documentRefString = saveDocument.collection("Posts").document(docId) {}
at let documentRefString error message camee out.
Initializer for conditional binding must have Optional type, not 'DocumentReference'
Tell me How to fix this error.

Remove if Let because documentRefString is not optional ... and you cant apply if let on non optionals
saveDocument.collection("Posts").document(docId)
Does not return optional value so change this line to
let documentRefString = saveDocument.collection("Posts").document(docId)
And use documentRefString safely

Related

getting the output Optional("test") [duplicate]

This question already has answers here:
Unable to remove "Optional" from String
(2 answers)
Closed 2 years ago.
I tried the following code
if let shortURL = shortURL {
var url = "\(shortURL.absoluteString)"
MUser.sharedInstance.setMobileReferralId(url)
self.referralLink.text = url self.copyToClipboard()
}
For the url variable, I get the output Optional("Test"). How do I remove the "Optional" part?
The reason looks like absoluteString is optional so you can provide a default value or using if let to assign its value to url, like below
if let url = shortURL.absoluteString {
print(url)
}
or provide some default blank value like
var url = shortURL.absoluteString ?? ""
print(url)
To remove the Optional part, you only need to unwrap optional right. example:
if let shortURL = shortURL,
let url = shortURL.absoluteString {
print(url)
}

How can save the text of the label as an integer variable in swift?

I need to save the changing text of my label as a variable, but if write the following code:
var warn = Int(self.dyn.text)
It says:
Value of optional type 'String?' must be unwrapped to a value of type 'String'
Coalesce using '??' to provide a default when the optional value contains 'nil'
Force-unwrap using '!' to abort execution if the optional value contains 'nil'
What code should I use?
var warn = Int(self.dyn.text ?? "") ?? 0
You have to provide a default value, just in case it's not possible to make the cast to Int. You also have to make sure the text value is not nil.
Take a look at optional chaining and optional binding
Another approach is:
if let dynText = self.dyn.text {
if let warn = Int(dynText) {
// warn is an available int variable here.
}
}
2 way of doiing that
1: let warn = Int(self.dyn.text ?? "") ?? 0
2: let warn = Int(self.dyn.text!)!
Good. Because String can be "123" or "Hello,world" so it can be numeric or String text
When you use this
Int(String) the initializer might fail, it returns an optional Int, rather than an Int
Example
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber is inferred to be of type "Int?", or "optional Int"
So you have to Unwrap it
Like that
// unwrap text if TextField is not `!` and then unwrap text when you convert to Int
if let dynText = self.dyn.text , let warn = Int(dynText) {
print(warn)
}

Checking for null value (not nil or NSnull) in swift always return nil? [duplicate]

This question already has answers here:
How is optional binding used in swift?
(9 answers)
Closed 6 years ago.
I am working on a project which uses both swift an objective c. The team member before me have written this code in objective C ,which I am not familiar with. There is problem that most of the part involving storing and retrieving value from Sqlite is in obj C. This has been done in a common class to avoid Code redemption. However if i use swift to retrieve value through that obj C file a problem occur. If there is no value in that specified row it return "null".
Update: Checked for optional binding as said by Antony Raphel
Even if i check for nil directly before converting to 'as? String' the same error persist. I came to know that there is no equivalent of "null" in swift. Is there any hack to the value is empty (null) in swift?
Just replace your
var prevNotifCount = self.cmmn.getPreviousNotificationCount() as? String
and use
guard let prevNotifCount = self.cmmn.getPreviousNotificationCount() else{
print("No previous notification value")
return
}
no need to check for nil, if it will fail , else block will be executed
if let prevNotifCount = self.cmmn.getPreviousNotificationCount() as? String
{
self.cmmn.saveInDatabase("19", phoneNumber: "0", otp: "0")
print(self.cmmn.getPreviousNotificationCount())
}
else
{
print("No previous notification value")
}
This is standard Swift approach called optional binding. You safely unwrap an optional and if it is not nil assign it to a local variable
Try by adding if let to check nil condition like this:-
if let NotifCount = self.cmmn,getPreviousNotificationCount() as? String
{
prevNotifCount = NotifCount
}
Please try this, Hope it helps!
Use if let statement.
if let preNotifCount = self.cmmn.getPreviousNotofication {
//business logic
}
Now business logic would only be executed if preNotifCount is not nil.

Swift 2 query printing with Optional wording [duplicate]

This question already has answers here:
swift How to remove optional String Character
(14 answers)
Closed 6 years ago.
let username = self.user?.getProperty("username") as? String
self.navigationItem.title = "#\(username)"
What I want to happen there is for it to print on the screen that users username with an # in front of it like #user2
What it is printing instead is #Optional("user2")
How do I make this stop that? Ha
String Interpolation prints also literal Optional(...) if the value is an optional.
To avoid that use either optional binding
if let username = self.user?.getProperty("username") as? String {
self.navigationItem.title = "#\(username)"
}
Or the ternary conditional operator
let username = self.user?.getProperty("username") as? String
self.navigationItem.title = username != nil ? "#\(username!)" : ""
In the first example the title won't be updated if username is nil, in the second it's updated with an empty string.

Unwrapping a optional in swift which is an optional but swift doesn't know its a optional

I'm working on an app to convert model paint color's. I just got coreData to work and now I ran into a different problem.
let colorL: String = String(color.valueForKey("revell"))
let AmountL: String = String(color.valueForKey("filled"))
print(colorL)
print(AmountL)
cell.ColorLabel.text = colorL
cell.AmountLabel.text = AmountL
This is my code for the tableview. and my console output is this
Optional(68)
Optional(g)
and so the problem is if you haven't guessed yet that I need to unwrap a optional that cannot be unwrapped because swift doesn't know it is a optional and I keep on getting a error that I can't unwrap a non-optional.
valueForKey returns an optional (AnyObject? to be specific). Unwrap that and then build a string with it.
if let value = color.valueForKey("revell") as? /* Some Type */ {
let amountL: String = String(value)
// ...
}
let colorL: String = (color.valueForKey("revell")?.description)!
let AmountL: String = (color.valueForKey("filled")?.description)!
print(colorL)
print(AmountL)
ColorLabel.text = colorL
AmountLabel.text = AmountL

Resources