Swift 2 query printing with Optional wording [duplicate] - ios

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.

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

sort an array by comparing a string value swift [duplicate]

This question already has answers here:
Sorting array alphabetically with number
(8 answers)
Closed 4 years ago.
I'm trying to sort an array by comparing a string value from two items, the values of the property are a number but of type String. How can I convert them to Int and check which is greater. Current code looks like this.
libraryAlbumTracks = tracks.sorted {
$0.position!.compare($1.position!) == .orderedAscending
}
but values like "13" come before "2" because it's a string. I tried to cast the values to Int but because they are optional, I get the error that operand ">" cannot be applied to type Int?
Please how can I go around this in the sorted function?
Provide the numeric option when using compare. This will properly sort strings containing numbers and it also works if some of the string don't actually have numbers or the strings have a combination of numbers and non-numbers.
libraryAlbumTracks = tracks.sorted {
$0.position!.compare($1.position!, options: [ .numeric ]) == .orderedAscending
}
This avoids the need to convert the strings to Int.
Note: You should also avoid force-unwrapping position. Either don't make them optional if it's safe to force-unwrap them, or safely unwrap then or use ?? to provide an appropriate default when comparing them.
libraryAlbumTracks = tracks.sorted {
guard let leftPosition = $0.position,
let leftInt = Int(leftPosition),
let rightPosition = $1.position,
let rightInt = Int(rightPosition) else {
return false
}
return leftInt > rightInt
}

Capitalize each first letter of the words in a string [duplicate]

This question already has answers here:
How to capitalize each word in a string using Swift iOS
(8 answers)
Closed 5 years ago.
How can i capitalized each first letter of the result of this
self.namE.text = currentUser.displayName
self.handle.text = snapshotValue?["handle"] as? String
instead of "Bruce willis" i would like to have "Bruce Willis", i created this extension to capitalized the first letter
extension String {
func capitalizingFirstLetter() -> String {
return prefix(1).uppercased() + dropFirst()
}
}
but it obviously capitalize only the first word in a string, so how i have to modify this extension to get the right result? ( i looked in the doc but i didn't understand very well )
String in swift4 has already a capitalized computed property on itself, so without implementing anything yourself, you can get the desired result using this:
self.namE.text = currentUser.displayName.capitalized
E.g.:
self.namE.text = "bruce willis".capitalized

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.

String concate issues in swift 3 [duplicate]

This question already has an answer here:
Swift 3 incorrect string interpolation with implicitly unwrapped Optionals
(1 answer)
Closed 6 years ago.
I am creating username from first and last name. It was working fine with swift 2.2 but after migrating to swift 3 now the string do get concate but when it does the first name is have optional with it. Check below images
use like this
let name = "\(firstName!) \(lastName)"
I have tried with basic example too. If string contain optional("") then you can resolve it by this by force the compiler to implicitly force unwrap.
you can check in .playground
let firstname : String!
let lastname : String!
firstname = "Hello" ==> "Hello"
lastname = "World" ==> "World"
let fullname = "\(firstname) \(lastname)" ==> "Optional("Hello") Optional("World")"
let fullname = "\(firstname!) \(lastname!)" ==> "Hello World"
Give it a try using above solution, Hope it Helps!

Resources