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

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)
}

Related

Swift Encode Custom String to populate URL [duplicate]

This question already has answers here:
Swift - encode URL
(19 answers)
Closed 2 years ago.
I have a URL that takes any String like this:
https://test#api.search?query=\(productSearchString)&limit=1
Now my problem is that this works with for example "iphone" but it crashes with "iphone 12".
I tried encoding it like this:
guard let escapedResourceString = resourceString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else { return }
but this doesn't seem to work in my case because it is returning an incorrect URL that I can not use with my API.
How can I fix this, so the user can type in anything he want but the URL should be created and my API should be able to work with it.
If you need anything more just let me know.
Your parameters needs to be url encoded.
You can use URLComponents to create your URL and pass your parameters as URLQueryItem instances, like that:
let productSearchString = "iphone 12"
var urlComponents = URLComponents(string: "https://test#api.search")
urlComponents?.queryItems = [
URLQueryItem(name: "query", value: productSearchString),
URLQueryItem(name: "limit", value: "1")
]
let url = urlComponents?.url
print(url?.absoluteString ?? "nil") // https://test#api.search?query=iphone%2012&limit=1

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

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

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.

Concatenating an optional and a string

I have a url variable declared like this
var url:String!
url = 'hello'
then I have the base url declared like this:
var baseUrl:String
baseUrl = http://google.com/
Trying to concatenate the 2 values together like
if let tmpurl = url {
println(baseUrl + tmpurl);
}
prints out
http://google.com/Optional('hello')
Why is there the Optional part in the output? I thought the let part would unwrap the optional
The very first thing is that you are using an older version of swift. Please update to 2.1. Secondly this is because you have unwrapped the url variable but its not required. So update your code as:
For swift 2.0
var url:String?
url = 'hello'
var baseUrl:String?
baseUrl = http://google.com/
if let tmpurl = url {
print(baseUrl! + tmpurl);
}

Swift NSURL error while creating [duplicate]

This question already has answers here:
Swift - encode URL
(19 answers)
Closed 7 years ago.
This is my code. Error: fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) I have no idea where;s the problem
res = "https://www.example.com/range.php?arr1=48.15&arr2=48.15&API_KEY=>code"
let url = NSURL(string: res)! // error line
print("url craeted" + res)
return url
The combination => leads to an instruction failure and let's the string not be interpreted as a string.
By the way, I assume res has been defined somewhere else in your code and you want to change "url created" into "url created", later.
You can use an extension to encode your URL
extension String {
func urlEncodedString() -> String {
let urlEncodedString = self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
return urlEncodedString ?? self
}
}

Resources