76

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....

hahaha
  • 1,379
  • 4
  • 11
  • 22

14 Answers14

118

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 optionalVariable : String? // This is an optional.
optionalVariable = "I am a programer"
print(optionalVariable) // Optional("I am a programer")
        
var nonOptionalVariable : String // This is not optional.
nonOptionalVariable = "I am a programer"
print(nonOptionalVariable) // "I am a programer"

//There are different ways to unwrap optional varialble

// 1 (Using if let or if var)
if let optionalVariable1 = optionalVariable {
    print(optionalVariable1)
}

// 2 (Using guard let or guard var)
guard let optionalVariable2 = optionalVariable else {
    fatalError()
}
print(optionalVariable2)

// 3 (Using default value ?? )
print(optionalVariable ?? "default value") // If variable is empty it will return default value

// 4 (Using force caste !)
print(optionalVariable!) // This is unsafe way and may lead to crash
Rajesh Maurya
  • 3,026
  • 4
  • 19
  • 37
  • 2
    I know this is an old post, however I thought I would clear up a few points so if anyone come upon this now they will have the correct information. FIrst println is no print, next the line var temp1: String! does not require the ! you only need to write var temp1: String //This is not an optional. Also on the temp example you can print the value of temp without having the Optional() simply by writing print(temp!) // "I am a programer" of course if the value of temp is nil using the ! will cause an error, so it is better to use if let or guard to protect your code from a nil. – Mark Dail Jun 29 '17 at 16:02
  • 1
    `This is not optional` Wrong, it is an IUO, an "implicitly unwrapped optional". Its value is automatically unwrapped when accessed. If it is nil, the app will crash. – Eric Aya May 08 '18 at 11:33
  • @Moritz Please look into the question. It is not about the crash, – Rajesh Maurya May 09 '18 at 10:57
  • I know what the question is about, ahah. What I'm telling you is that what you're saying is *wrong*. The line where you say "This is not optional", you're wrong, this *is* an optional, it's an implicitly unwrapped optional. – Eric Aya May 09 '18 at 11:02
55

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.

GregP
  • 1,584
  • 17
  • 16
25

You need to unwrap the optional before you try to use it via string interpolation. The safest way to do that is via optional binding:

if let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex) {
    println(color) // "Red"

    let imageURLString = "http://hahaha.com/ha.php?color=\(color)"
    println(imageURLString) // http://hahaha.com/ha.php?color=Red
}
Mike S
  • 41,895
  • 11
  • 89
  • 84
  • @user1272854 the code in my answer should do what you want. Is your code different from what you posted in the question somehow? – Mike S Oct 14 '14 at 15:03
12

In swift3 you can easily remove optional

if let value = optionalvariable{
 //in value you will get non optional value
}
Mahesh Giri
  • 1,810
  • 19
  • 27
  • 1
    I like this. Even though it's a bit more code involved, it's safe, it's clean, AND, you can perform actions if the optional is nil, without having to check it somewhere else. – Septronic Jan 01 '17 at 18:35
  • Haha I've been using it so often without actually knowing what it does. Now I specifically needed it and didn't know how to search for :D Thanks a lot and no @MaciejSwic this is how it's supposed to be done – user2875404 Oct 19 '17 at 20:08
11

Check for nil and unwrap using "!":

let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex)

println(color) // Optional("Red")

if color != nil {
    println(color!) // "Red"
    let imageURLString = "http://hahaha.com/ha.php?color=\(color!)"
    println(imageURLString)
    //"http://hahaha.com/ha.php?color=Red"
}
yh_sss
  • 119
  • 1
  • 2
  • 1
    This works, but force unwrapping optionals is really bad practice. You are throwing away all of the type safety that Swift gives you. Using `if let` or `guard` to bind optional to a constant variable. (See Mike's answer) – Kevin Sep 09 '15 at 16:54
6

Besides the solutions mentioned in other answers, if you want to always avoid that Optional text for your whole project, you can add this pod:

pod 'NoOptionalInterpolation'

(https://github.com/T-Pham/NoOptionalInterpolation)

The pod adds an extension to override the string interpolation init method to get rid of the Optional text once for all. It also provides a custom operator * to bring the default behaviour back.

So:

import NoOptionalInterpolation
let a: String? = "string"
"\(a)"  // string
"\(a*)" // Optional("string")

Please see this answer https://stackoverflow.com/a/37481627/6390582 for more details.

Community
  • 1
  • 1
Thanh Pham
  • 2,021
  • 21
  • 30
4

Try this,

var check:String?="optional String"
print(check!) //optional string. This will result in nil while unwrapping an optional value if value is not initialized or if initialized to nil.
print(check) //Optional("optional string") //nil values are handled in this statement

Go with first if you are confident to have no nil in your variable. Also, you can use if let or Guard let statement to unwrap optionals without any crash.

 if let unwrapperStr = check
 {
    print(unwrapperStr) //optional String
 }

Guard let,

 guard let gUnwrap = check else
 {
    //handle failed unwrap case here
 }
 print(gUnwrap) //optional String
Manoj Kumar
  • 318
  • 4
  • 14
  • 1
    This is not quite the case. In the first one, if you use print(check!) and the object is actually nil, it will crash your app. Adding an exclamation point unwraps the optional changing from a String? to a String. If it's nil, that will fail and cause a crash. – Matthew Knippen Oct 17 '16 at 13:48
  • People need to stop abusing the ! operator. Optionals are there because the idea of an optional is that you want to allow for the possibility that the variable can be nil. Like @MatthewKnippen said, if you force unwrap an optional that is nil, then the app will crash. If you need to force unwrap optionals, then you probably shouldn't be using optionals to begin with. At the very least you should use an `if let` or `guard let else` unwrap to make sure it is not nil. – Clayton C. Dec 11 '16 at 07:16
1

Simple convert ? to ! fixed my issue:

usernameLabel.text = "\(userInfo?.userName)"

To

usernameLabel.text = "\(userInfo!.userName)"
Payam Khaninejad
  • 7,692
  • 6
  • 45
  • 55
1

Although we might have different contexts, the below worked for me.

I wrapped every part of my variable in brackets and then added an exclamation mark outside the right closing bracket.

For example, print(documentData["mileage"]) is changed to:

print((documentData["mileage"])!)
SemperFi
  • 2,358
  • 6
  • 31
  • 51
tonderaimuchada
  • 215
  • 2
  • 6
0
import UIKit

let characters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

var a: String = characters.randomElement()!
var b: String = characters.randomElement()!
var c: String = characters.randomElement()!
var d: String = characters.randomElement()!
var e: String = characters.randomElement()!
var f: String = characters.randomElement()!
var password = ("\(a)" + "\(b)" + "\(c)" + "\(d)" + "\(e)" + "\(f)")

    print ( password)
  • 1
    Code only answers are not very helpful.Please add an explanation as to how this code solves the question – Arghya Sadhu Aug 15 '20 at 06:47
  • Question was too broad, and not specific. I am presenting, my case of how to remove printing Optional. I declared variables as string and unwrapped by adding exclamatory mark in the end. – ramesh babu Aug 16 '20 at 11:36
  • of course, its a long answer. I think answer given by Rajesh mourya is clear and simple – ramesh babu Aug 16 '20 at 11:39
0

when you define any variable as a optional then you need to unwrap that optional value.Convert ? to !

0

How do I remove optional String Character for Printing in Swift UIkit

From These (Have Optional printing)

print("Collection Cell \(categories[indexPath.row].title) \(indexPath.row)")

To these ( Doesn't have Optional printing)

print("Collection Cell \(categories[indexPath.row].title ?? "default value") \(indexPath.row)")
Chithian
  • 253
  • 3
  • 8
-1

print("imageURLString = " + imageURLString!)

just use !

SANTOSH
  • 183
  • 1
  • 15
-1

You can just put ! and it will work:

print(var1) // optional("something")

print(var1!) // "something"
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
itay
  • 43
  • 6