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
tymac Nov 07 '17 at 19:17 2017-11-07 19:17
source share