Last active
June 22, 2016 15:23
-
-
Save asowers1/4261e98a7276da6fc07b5f80180d70f1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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