只是想用swift从字符串中删除第一个字符。我使用下面写的代码,但是第二行代码一直在破坏我的应用程序。
这不是展开字符串索引的正确方法吗?是什么?
var tempText = text
let toRemove = tempText?.startIndex ?? String.Index(0)
tempText?.remove(at: toRemove)
最佳答案
您正在初始化String.Index
类型,而不是获取tempText
字符串的索引。
此外,startIndex
不是可选的,tempText
是可选的。
您应该检查tempText
是否存在且不为空(您只需使用if let
即可),如果符合这些条件,请删除startIndex
处的字符。
var tempText = text
if let toRemove = tempText?.startIndex {
tempText?.remove(at: toRemove)
}
关于swift - Swift的字符串基础,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46369662/