Github Gist:
https://gist.github.com/zhaorui/fd2fbb988b82981bdf7c8e6e550b6c08
StackOverflow 讨论:
http://stackoverflow.com/questions/34772439/see-characters-in-an-nscharacterset-swift
Unicode基本知识
http://www.ruanyifeng.com/blog/2014/12/unicode.html
代码原理
Unicode编码包含0..16共17个平面,遍历这17个平面,如果CharacterSet中有字符属于特定的平面的话,则遍历该平面,找出CharacterSet中在该平面的所有字符,添加到数组中作为返回。
Code (Swift3实现)
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)
网友评论