Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Optional String to String

Tags:

swift

optional

@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?

like image 961
Hanslen Chen Avatar asked Jan 27 '16 20:01

Hanslen Chen


2 Answers

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

like image 75
LHIOUI Avatar answered Sep 21 '22 04:09

LHIOUI


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.

like image 38
Luca Angeletti Avatar answered Sep 20 '22 04:09

Luca Angeletti