不推荐使用Swift 4:substring(with :)':请使用字符串切片下标

May*_*day 7 swift swift4

我正在使用html的解码功能.但是我收到了这个警告.我该如何摆脱?

func decode(_ entity : String) -> Character? {

    if entity.hasPrefix("&#x") || entity.hasPrefix("&#X"){
        return decodeNumeric(entity.substring(with: entity.index(entity.startIndex, offsetBy: 3) ..< entity.index(entity.endIndex, offsetBy: -1)), base: 16)
    } else if entity.hasPrefix("&#") {
        return decodeNumeric(entity.substring(with: entity.index(entity.startIndex, offsetBy: 2) ..< entity.index(entity.endIndex, offsetBy: -1)), base: 10)
    } else {
        return characterEntities[entity]
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

rma*_*ddy 21

someString.substring(with: someRange)只是需要someString[someRange].

所以改变:

entity.substring(with: entity.index(entity.startIndex, offsetBy: 3) ..< entity.index(entity.endIndex, offsetBy: -1))
Run Code Online (Sandbox Code Playgroud)

entity[entity.index(entity.startIndex, offsetBy: 3) ..< entity.index(entity.endIndex, offsetBy: -1)]
Run Code Online (Sandbox Code Playgroud)

换句话说,更改.substring(with:[并将结束更改)].

结果是Substring,而不是String.因此,您可能需要将结果包装起来String( )String从子字符串结果中获取a .