5

When I'm trying to list characters in an NSCharacterSet like this

print(NSCharacterSet.URLQueryAllowedCharacterSet())

it doesn't print out the characters but rather something similar to

<__NSCFCharacterSet: 0x1759b900>

Desmond Hume
  • 8,037
  • 14
  • 65
  • 112

1 Answers1

13

Based on another answer, here is a derived cleaner version in Swift 2.0/3.0:

extension NSCharacterSet {
    var characters:[String] {
        var chars = [String]()
        for plane:UInt8 in 0...16 {
            if self.hasMemberInPlane(plane) {
            let p0 = UInt32(plane) << 16
            let p1 = (UInt32(plane) + 1) << 16
            for c:UTF32Char in p0..<p1 {
                    if self.longCharacterIsMember(c) {
                        var c1 = c.littleEndian
                        let s = NSString(bytes: &c1, length: 4, encoding: String.Encoding.utf32LittleEndian.rawValue)!
                        chars.append(String(s))
                    }
                }
            }
        }
        return chars
    }
}

Usage:

let charset = NSCharacterSet.URLQueryAllowedCharacterSet()
print(charset.characters.joinWithSeparator(""))
Desmond Hume
  • 8,037
  • 14
  • 65
  • 112
  • Please replace "based on another answer" by a link to the answer(s) that your code is based on. – Martin R Jan 13 '16 at 17:51
  • @MartinR Sure. Done. A notable change is replacing `++` with `+= 1` for the newest Swift versions. – Desmond Hume Jan 13 '16 at 18:02
  • Why didn't you add it as another answer to that thread, so that people find the information at a single place? I am tempted to close as a duplicate again. – Btw, C-style for-loops will be removed from Swift as well :) – Martin R Jan 13 '16 at 18:08
  • @DesmondHume be aware that C-style for-loops with conditions and increments will not be available with Swift 3 https://github.com/apple/swift-evolution/blob/master/proposals/0007-remove-c-style-for-loops.md – Leo Dabus Jan 13 '16 at 20:16
  • @LeoDabus Made edits for Swift 3 – Desmond Hume Jan 14 '16 at 10:51
  • This answer is correct. And I have some improvement on it with Swift 4. How about use the lazy feature of collection. [LazyCharacters in CharacterSet](https://github.com/KeithPiTsui/Pavers/blob/swift4.2/Pavers/Sources/FRP/Extension/CharacterSetExtension.swift) – Keith Jul 11 '18 at 03:04
  • General advice: don’t run this in a playground. Takes hours. – mxcl Sep 26 '19 at 13:26