Skip to content

Instantly share code, notes, and snippets.

@asowers1
Last active June 22, 2016 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asowers1/4261e98a7276da6fc07b5f80180d70f1 to your computer and use it in GitHub Desktop.
Save asowers1/4261e98a7276da6fc07b5f80180d70f1 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
var str1 = "Hello, playground 💩"
var str2 = "Hello, playground"
func validate(ascii string: String?) -> Bool {
if let str = string where str.characters.count > 0 {
for char in str.characters {
let byteArr = Array(String(char).utf8)
if let firstByte = byteArr.first
where byteArr.count == 1 && (firstByte >= 0 && firstByte < 128) {
// this char is valid
} else {
return false
}
}
return true
}
return false
}
validate(ascii: str1) // this is false
validate(ascii: str2) // this is true
// if you wanted to add this code as a class level extension to String, it would look something like this:
extension String {
func validateAscii() -> Bool {
if self.characters.count > 0 {
for char in self.characters {
let byteArr = Array(String(char).utf8)
if let firstByte = byteArr.first
where byteArr.count == 1 && (firstByte >= 0 && firstByte < 128) {
// this char is valid
} else {
return false
}
}
return true
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment