warning: 'characters' is deprecated: Please use String or Substring directly

One of the most common cases for manipulating strings is with JSON responses. In this example I created an extension in my watch app to drop the last (n) characters of a Bitcoin JSON object.

Swift 3:

func dropLast(_ n: Int = 0) -> String {
    return String(characters.dropLast(n))

Xcode 9.1 Error Message:

'characters' is deprecated: Please use String or Substring directly

Xcode is telling us to use the string variable or method directly.

Swift 4:

func dropLast(_ n: Int = 0) -> String {
    return String(dropLast(n))
    }

Complete Extension:

extension String {
    func dropLast(_ n: Int = 0) -> String {
        return String(dropLast(n))
    }

    var dropLast: String {
        return dropLast()
    }
}

Call:

print("rate:\(response.USDRate)")
let literalMarketPrice = response.USDRate.dropLast(2)
print("literal market price: \(literalMarketPrice)")

Console:

//rate:7,101.0888 //JSON float
//literal market price: 7,101.08 // JSON string literal

Additional Examples:

  • print("Spell has \(invisibleSpellName.count) characters.")
  • return String(dropLast(n))
  • return String(removeLast(n))

Documentation:

You'll often be using common methods such as dropLast() or removeLast() or count so here is the explicit Apple documentation for each method.

droplast()

removelast()

counting characters


Swift 4 introduced changes on string API.
You can just use !stringValue.isEmpty instead of stringValue.characters.count > 0

for more information you get the sample from here

for e.g

let edit = "Summary"
edit.count   // 7

Swift 4 vs Swift 3 examples:

let myString = "test"

for char in myString.characters {print(char) } // Swift 3
for char in myString { print(char) } // Swift 4

let length = myString.characters.count // Swift 3
let length = myString.count // Swift 4