Hanslen Chen
Hanslen Chen

Reputation: 440

How to convert Optional String to String

@IBOutlet var navBar: UINavigationBar!
@IBOutlet var menuButton: UIBarButtonItem!
@IBOutlet var topicNameLabel: UILabel!
var topicName:String!
override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    menuButton.target = self.revealViewController()
    menuButton.action = Selector("revealToggle:")

    navBar.barTintColor = UIColor(red: 0, green: 0.4176, blue: 0.4608, alpha: 1)
    topicNameLabel.text = self.topicName

}

That's my code, I will pass a string to the topicName by prepareForSegue, however, I find that in the simulator, my topicNameLabel shows "Optional(The text I want)". I just want the "The text I want", but do not need the Optional. Could any one help me?

Upvotes: 8

Views: 36439

Answers (3)

user5965345
user5965345

Reputation:

I think your problem is your string really contains with a "optional", you can try indexAt(0) to see is "o" or not.

Upvotes: 3

Luca Angeletti
Luca Angeletti

Reputation: 59496

The problem is not here

Your property is declared as an implicitly unwrapped optional String.

var topicName: String!

So when you use it the value is automatically unwrapped.

Example:

var topicName:String!
topicName = "Life is good"
print(topicName)

Output

Life is good

As you can see there is no Optional(Life is good) in the output. So this code is correct.

My theory

My guess is that you are populating topicName with a String that already contains the Optional(...) word.

This is the reason why you are getting the Optional(...) in the output.

Testing my theory

To test this scenario let's add an observer to your property

willSet(newValue) {
    print("topicaName will be set with this: \(newValue)")
}

I expect you will see something like this in the log

topicaName will be set with this: Optional(Hello)

Finding the real problem (aka who is writing the String 'Optional("Hello")'?)

If this does happen just put a breakpoint in the observer and find the instruction in your project that is writing the String Optional("Hello") in your property.

Upvotes: 5

LHIOUI
LHIOUI

Reputation: 3337

Optional string means that the string may be nil. From "The Basics" in the Swift Programming Language

Swift also introduces optional types, which handle the absence of a value.

When you print an optional string on console it will tell you that it is an optional. So the value of the string dos not contain the "Optional" keyword...

For example

var str : String?
str = "Hello" // This will print "Optional("Hello")"
print(str)
print(str!) // This will print("Hello") 

But str value is "Hello" . It is an optional string

Upvotes: 10

Related Questions