Warning: "characters" are deprecated: use String or Substring directly

characters - String instance property, deprecated since Xcode 9.1 (beta)

This is / a very useful property to get a substring from String, but not to become obsolete, and Xcode suggests using substring . I tried to check the SO questions and tutorials for Apple developers / recommendations for them. But did not see any solution / alternative as intended.

Here is a warning:

"characters" are deprecated: use String or Substring

enter image description here

I have so many string operations performed / processed using the characters property.

Anyone have any idea / info on this update?

+67
string substring ios swift4 xcode9.1-beta
Sep 28 '17 at 10:49 on
source share
4 answers

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

For more information you will receive a sample from here.

eg,

 let edit = "Summary" edit.count // 7 
+121
Sep 28 '17 at 10:54 on
source share

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 
+14
Nov 08 '17 at 11:11
source share

This warning is just the tip of the iceberg, there were loot of string changes, the lines again are a set of characters, but we have new and cool substrings :)

It's great to read about it: https://useyourloaf.com/blog/updating-strings-for-swift-4/

+2
Nov 03 '17 at 14:40
source share

One of the most common cases of string manipulation is JSON responses. In this example, I created an extension in the watch application to remove the last (n) characters of the Bitcoin JSON object.

Swift 3:

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

Xcode 9.1 Error Message:

'characters' is deprecated: use a string or substring directly

Xcode tells us to use a string variable or method directly.

Swift 4:

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

Full 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:

Often you'll use generic methods like dropLast() or removeLast() or count , so here's the explicit Apple documentation for each method.

droplast ()

removeelast ()

character count

0
Nov 07 '17 at 19:17
source share



All Articles