Github Gist:
https://gist.github.com/zhaorui/fd2fbb988b82981bdf7c8e6e550b6c08
StackOverflow 討論:
http://stackoverflow.com/questions/34772439/see-characters-in-an-nscharacterset-swift
Unicode基本知識(shí)
http://www.ruanyifeng.com/blog/2014/12/unicode.html
代碼原理
Unicode編碼包含0..16共17個(gè)平面,遍歷這17個(gè)平面,如果CharacterSet中有字符屬于特定的平面的話,則遍歷該平面,找出CharacterSet中在該平面的所有字符,添加到數(shù)組中作為返回。
Code (Swift3實(shí)現(xiàn))
extension CharacterSet {
var characters:[UnicodeScalar] {
var chars = [UnicodeScalar]()
for plane:UInt8 in 0...16 {
if self.hasMember(inPlane: plane) {
let p0 = UInt32(plane) << 16
let p1 = (UInt32(plane) + 1) << 16
for c:UInt32 in p0..<p1 {
if let us = UnicodeScalar(c) {
if self.contains(us) {
chars.append(us)
}
}
}
}
}
return chars
}
}
使用范例
print(CharacterSet.urlQueryAllowed.characters)