Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 : substring(with:)' is deprecated: Please use String slicing subscript [duplicate]

Tags:

swift

swift4

I am using a decode function for html. But I am getting this warning. How can I get rid off?

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]
    }
}

Thank you.

like image 695
Mayday Avatar asked Oct 14 '17 21:10

Mayday


1 Answers

The someString.substring(with: someRange) just needs to be someString[someRange].

So change:

entity.substring(with: entity.index(entity.startIndex, offsetBy: 3) ..< entity.index(entity.endIndex, offsetBy: -1))

with

entity[entity.index(entity.startIndex, offsetBy: 3) ..< entity.index(entity.endIndex, offsetBy: -1)]

In other words, change the .substring(with: to [ and change the closing ) to ].

The result is a Substring, not String. So you may need to wrap the result in String( ) to get a String from the substring result.

like image 133
rmaddy Avatar answered Sep 28 '22 02:09

rmaddy