如何将可选字符串转换为字符串

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

}

那是我的代码,我将通过 prepareForSegue 将一个字符串传递给 topicName,但是,我发现在模拟器中,我的 topicNameLabel 显示 "Optional(The text I want)"。我只想要 "The text I want",但不需要 Optional。谁能帮帮我?

可选字符串表示该字符串可以为nil。 来自 "The Basics" in the Swift Programming Language

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

当您在控制台上打印可选字符串时,它会告诉您它是可选的。所以字符串的值不包含"Optional"关键字...

例如

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

但是 str 值是 "Hello" 。它是一个可选的字符串

问题不在这里

您的 属性 被声明为 implicitly unwrapped optional String

var topicName: String!

所以当你使用它时,值会自动展开。

示例:

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

输出

Life is good

如您所见输出中没有 Optional(Life is good)。 所以这段代码是正确的。

我的理论

我的猜测是您正在使用已经包含 Optional(...) 单词的 String 填充 topicName

这就是您在输出中得到 Optional(...) 的原因。

检验我的理论

为了测试这种情况,让我们向您的 属性

添加一个观察者
willSet(newValue) {
    print("topicaName will be set with this: \(newValue)")
}

我希望您会在日志中看到这样的内容

topicaName will be set with this: Optional(Hello)

找到真正的问题(也就是谁在写字符串 'Optional("Hello")'?)

如果确实发生这种情况,只需在观察者中放置一个断点,然后在您的项目中找到在您的 属性.

中写入字符串 Optional("Hello") 的指令

我认为你的问题是你的字符串确实包含 "optional",你可以试试 indexAt(0) 看看是不是 "o"。