String.CharacterView - 如何转换为String

时间:2017-04-11 11:36:18

标签: swift swift3

我尝试了以下内容:

let str = self.passwordLabel.text?.characters.dropLast()
let s = String(describing: str)

但它给了我以下内容:

"Optional(Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: Optional(0x0000618000051e10), _countAndFlags: 9223372036854775810, _owner: Optional(Swift._HeapBufferStorage<Swift._StringBufferIVars, Swift.UInt16>)), _coreOffset: 0))"

我只想删除字符串中的最后一个字符?

2 个答案:

答案 0 :(得分:3)

您需要打开可选字符串并且不要使用describing初始化程序。

if let passwordText = self.passwordLabel.text {
    let s = String(passwordText.characters.dropLast())
}

或保证text不是nil

let s = String(self.passwordLabel.text!.characters.dropLast())

答案 1 :(得分:2)

请勿使用String(describing:...)并解开可选的str

let passwordLabel = UILabel()
passwordLabel.text = "TEXT1"
if let str = passwordLabel.text?.characters.dropLast() {
    let s = String(str)
    print(s)
}

打印:TEXT