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