Swift 3

时间:2016-11-09 11:57:20

标签: ios swift nsstring swift3

这是我的代码的一部分:

let separator = anyWord.indexOf("-")!
if (separator >= 0) {
let res = anyWord[anyWord.characters.index(after: separator)..<anyWord.endIndex] //get an error
//some code
}

我在'let res'部分出错了 - 输入'String!'没有下标成员

如果我这样做:

let separator = anyWord.indexOf("-")!
let subStartIndex = anyWord.characters.index(after: separator)

String的扩展名:

extension String {
    public func indexOf(_ char: Character) -> Int! {
        if let idx = self.characters.index(of: char) {
            return self.characters.distance(from: self.startIndex, to: idx)
        }
        return Const.INVALID_VALUE
    }

我收到错误:

  

字符串不能用'Int'索引,它有可变大小的元素

3 个答案:

答案 0 :(得分:2)

你认为太复杂了,使用range(ofupperBound

在Swift 3中很容易
let anyWord = "asdghf-fkgjh"
if let separator = anyWord.range(of:"-") {
   let res = anyWord.substring(from: separator.upperBound)
   //some code
}

答案 1 :(得分:0)

将其投射到字符串

let test: String
test = "Test-Word"
if let separatorWord = anyWord.range(of: "-") 
{
let word = anyWord.substring(from: anyWord.index(after:   
separatorWord.lowerBound))
print(word)
}

答案 2 :(得分:0)

我喜欢'纯'快速解决方案(不需要基金会)

let anyWord = "asdghf-fkgjh-blablabla--bla"
anyWord.characters.split(separator: "-").forEach { print( String($0)) }

打印

asdghf
fkgjh
blablabla
bla