0

I absolutely have no knowledge on xcode, swift, mac, etc, but I have to modify and a ready made project, just very little settings.

Everything is fine, but the following warning which I didn't understand how to fix it by googling and reading, because I don't know this language at all. I'll very thankful if someone kindly just write the equivalent swift 4 code for this:

WARNING:

'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator.

CODE:

hex = hex.substring(from: hex.characters.index(hex.startIndex, offsetBy: 1))
Kardo
  • 1,658
  • 4
  • 32
  • 52
  • Possible duplicate of https://stackoverflow.com/questions/46336932/swift-4-substringfrom-is-deprecated-please-use-string-slicing-subscript-wi?rq=1 or https://stackoverflow.com/questions/47304522/substringfrom-is-deprecated-please-use-string-slicing-subscript-with-a-pa?rq=1. – Martin R Feb 04 '18 at 10:22

1 Answers1

2

The warning wants you to do this:

hex = String(hex[hex.index(hex.startIndex, offsetBy: 1)...])

Notes:

  • hex.characters is deprecated in Swift 4; use hex directly.
  • [index...] is the slicing subscript with a 'partial range from' operator. It says create a substring from index to the end of the string. In this case, index is hex.index(hex.startIndex, offsetBy: 1) which is just the index of the second character of the string. Applying this slicing operator to hex creates a substring with all characters of hex from the second character to the end of the string.
  • The only problem is that the slicing operator returns a substring of type String.SubSequence instead of String. The String() is necessary to convert the String.SubSequence returned by the slicing operator back into a String.

A Better Way

All this line of code is doing is dropping the first character from the String. In Swift 4, there is a better way:

hex = String(hex.dropFirst())

Notes:

  • dropFirst() returns a String.SubSequence so it is necessary to use String() to convert that back into a String.
  • This is actually better than the original code, because it won't crash when given an empty string "".
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • I'd highly appreciate if you also take a look at my other question: https://stackoverflow.com/questions/48598578/how-to-fix-uialertview-was-deprecated-in-ios-9-0-uialertview-is-deprecated – Kardo Feb 04 '18 at 14:23