Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift How to remove optional String Character

Tags:

string

swift

How do I remove Optional Character


let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex)  println(color) // Optional("Red")  let imageURLString = "http://hahaha.com/ha.php?color=\(color)" println(imageURLString) //http://hahaha.com/ha.php?color=Optional("Red") 

I just want output "http://hahaha.com/ha.php?color=Red"

How can I do?

hmm....

like image 457
hahaha Avatar asked Oct 13 '14 19:10

hahaha


People also ask

How do I remove optional text in Swift?

If my assumption is incorrect, then one quick hack you can quickly do to get rid of the "Optional" in the text is to change your strings to force unwrap item , like so: theYears. text = "\(item!. experience)" .

How do I remove a character from a string in Swift?

To remove the specific character from a string, we can use the built-in remove() method in Swift. The remove() method takes the character position as an argument and removed it from the string.

What is an optional string in Swift?

An optional in Swift is basically a constant or variable that can hold a value OR no value. The value can or cannot be nil. It is denoted by appending a “?” after the type declaration. For example: var tweet: String?


2 Answers

Actually when you define any variable as a optional then you need to unwrap that optional value. To fix this problem either you have to declare variable as non option or put !(exclamation) mark behind the variable to unwrap the option value.

var temp : String? // This is an optional. temp = "I am a programer"                 print(temp) // Optional("I am a programer")  var temp1 : String! // This is not optional. temp1 = "I am a programer" print(temp1) // "I am a programer" 
like image 92
Rajesh Maurya Avatar answered Sep 18 '22 18:09

Rajesh Maurya


I looked over this again and i'm simplifying my answer. I think most the answers here are missing the point. You usually want to print whether or not your variable has a value and you also want your program not to crash if it doesn't (so don't use !). Here just do this

    print("color: \(color ?? "")") 

This will give you blank or the value.

like image 34
GregP Avatar answered Sep 17 '22 18:09

GregP