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....
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)" .
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.
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?
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With