我想为 string 做一个子字符串扩展,我尝试了以下两种方法但没有成功:
extension String
{
func substringToFirstChar(of char: Character) -> String
{
let pos = self.range(of: String(char))
let subString = self[..<pos?.lowerBound]
return String(subString)
}
}
或者
extension String
{
func substringToFirstChar(of char: Character) -> String
{
let pos = self.index(of: char)
let subString = self[..<pos]
return String(subString)
}
}
怎么做 ?
最佳答案
range(of
/index(of
返回一个可选的。您必须在范围表达式中解开可选项
extension String
{
func substringToFirstChar(of char: Character) -> String?
{
guard let pos = self.range(of: String(char))?.lowerBound else { return nil }
// or guard let pos = self.index(of: char) else { return nil }
let subString = self[..<pos]
return String(subString)
}
}
或者 - 避免可选 - 如果没有匹配,则返回未更改的字符串
extension String
{
func substringToFirstChar(of char: Character) -> String
{
guard let pos = self.range(of: String(char))?.lowerBound else { return self }
// or guard let pos = self.index(of: char) else { return self }
let subString = self[..<pos]
return String(subString)
}
}
关于xcode - 无法推断通用参数 'Self' (swift 4),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48112544/