0

I've got a function that parses some hexadecimal data, however, I have to substring the data manually as well as convert it to bytes. The following is what I have:

public func parseHex(hex: String) {
    self.address = UInt8(hex.substring(0...4))
}

Where self.address is a UInt8 field. The error I'm getting is:

Argument labels '(_:)' do not match any overloads

How can I fix this?

Hamish
  • 78,605
  • 19
  • 187
  • 280
Bram
  • 2,718
  • 1
  • 22
  • 43
  • If you want a `UInt8`, surely you want a 2 character substring of the hex string? – Hamish Mar 20 '17 at 17:59
  • See [How does String substring work in Swift 3](http://stackoverflow.com/q/39677330/2976878) – Hamish Mar 20 '17 at 18:00
  • Also see [this answer](http://stackoverflow.com/a/33733025/2976878) for a simple way to get (up to) the first n characters of a string. – Hamish Mar 20 '17 at 18:16

1 Answers1

0

As @Hamish stated you should use Collection extension method: public func prefix(_ maxLength: Int) -> Self.SubSequence

func parse(hexString: String) {
    self.address = UInt8(hexString.characters.prefix(4))
}

As an alternative can use bridging to NSString and use NSRange (but the first case is definitely better):

func parse(hexString: String) {
    let hexNSString = hexString as NSString
    self.address = UInt8(hexNSString.substring(with: NSRange(location: 0, length: 4)))
}
Oleh Zayats
  • 2,423
  • 1
  • 16
  • 26
  • How does this implement the substring? – Bram Mar 20 '17 at 17:58
  • @Craz1k0ek oh sorry, updated my answer, maybe it will suit your needs – Oleh Zayats Mar 20 '17 at 18:06
  • 1
    There's no need to bridge to `NSString`, you can use `String(hex.characters.prefix(2))` instead (or `hex[hex.startIndex...hex.index(after: hex.startIndex)]` if you want a crash for strings that are too short). Also you need to re-add `radix: 16` to parse the string as hex rather than decimal, and then unwrap the optional returned from the initialiser. Also also a length of 4 is too long for a single hex byte, unless the first two characters are both 0. – Hamish Mar 20 '17 at 18:24
  • @Hamish totally agree, added to the answer. Still I think question was not about parsing but about substrings – Oleh Zayats Mar 20 '17 at 18:32
  • @OlehZayats does this also work for the Int(string, radix: 16) – Bram Mar 20 '17 at 18:34