To validate UTF-8 bytes in Swift, you can use the String.Encoding.utf8 enumeration value to initialize a String.Encoding object, which can be used to validate the bytes using the String method init?(data: Data, encoding: String.Encoding).
Here's an example function that takes in a Data object and returns a Bool indicating whether the bytes are valid UTF-8:
main.swift164 chars8 linesYou can use this function like so:
main.swift393 chars10 linesNote that this validation only checks whether the bytes can be interpreted as valid UTF-8. It doesn't guarantee that the bytes actually represent valid Unicode characters.
gistlibby LogSnag