How to create a custom NSCharacterSet?
The most typical way to create a new character set is using
CharacterSet(charactersIn:)
, giving a String
with all the characters of the set.
Adding some characters to an existing set can be achieved using:
let characterSet = NSMutableCharacterSet() //create an empty mutable set
characterSet.formUnionWithCharacterSet(NSCharacterSet.URLQueryAllowedCharacterSet())
characterSet.addCharactersInString("?&")
or in Swift 3+ simply:
var characterSet = CharacterSet.urlQueryAllowed
characterSet.insert(charactersIn: "?&")
For URL encoding, also note Objective-C and Swift URL encoding
You can try my method:
let password = "?+=!@#$%^&*()-_abcdABCD1234`~"
// Swift 2.3
extension NSCharacterSet {
static var rfc3986Unreserved: NSCharacterSet {
let mutable = NSMutableCharacterSet()
mutable.formUnionWithCharacterSet(.alphanumericCharacterSet())
mutable.addCharactersInString("-_.~")
return mutable
}
}
let encoding = password.stringByAddingPercentEncodingWithAllowedCharacters(.rfc3986Unreserved)
// Swift 3
extension CharacterSet {
static var rfc3986Unreserved: CharacterSet {
return CharacterSet(charactersIn: "-_.~").union(.alphanumerics)
}
}
let encoding = password.addingPercentEncoding(withAllowedCharacters: .rfc3986Unreserved)
Print:
original -> ?+=!@#$%^&*()-_abcdABCD1234`~
encoding -> %3F%2B%3D%21%40%23%24%25%5E%26%2A%28%29-_abcdABCD1234%60~
rfc3986: https://www.rfc-editor.org/rfc/rfc3986