如何创建自定义 NSCharacterSet?

How to create a custom NSCharacterSet?

我正在使用 CharacterSet.urlQueryAllowed 向字符串添加百分比编码。

有些字符没有按照我预期的方式编码(即 &? 没有改变)。话虽这么说,我还是想构建一个自定义 CharacterSet,最好是基于现有的。

这样做的最佳方法是什么?

创建新字符集的最典型方法是使用 CharacterSet(charactersIn:),给出一个 String 和集合中的所有字符。

可以使用以下方法将一些字符添加到现有字符集中:

let characterSet = NSMutableCharacterSet() //create an empty mutable set
characterSet.formUnionWithCharacterSet(NSCharacterSet.URLQueryAllowedCharacterSet())
characterSet.addCharactersInString("?&")

Swift 3+ 只需:

var characterSet = CharacterSet.urlQueryAllowed
characterSet.insert(charactersIn: "?&")

对于URL编码,还要注意Objective-C and Swift URL encoding

你可以试试我的方法:

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