Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom NSCharacterSet?

I’m using CharacterSet.urlQueryAllowed to add percent-encoding to a String.

Some characters are not encoded the way I expected (i.e. & and ? are not changed). That being said, I had the idea to build a custom CharacterSet, ideally based on an existing one.

What’s the best approach to do so?

like image 984
ixany Avatar asked Sep 11 '15 16:09

ixany


People also ask

What is an example of a character set?

Examples of character sets include International EBCDIC, Latin 1, and Unicode. Character sets are chosen on the basis of the letters and symbols required. Character sets are referred to by a name or by an integer identifier called the coded character set identifier (CCSID).

What is CharacterSet in Swift?

CharacterSet (and its reference type counterpart, NSCharacterSet ) is a Foundation type used to trim, filter, and search for characters in text. In Swift, a Character is an extended grapheme cluster (really just a String with a length of 1) that comprises one or more scalar values.


2 Answers

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

like image 87
Sulthan Avatar answered Oct 02 '22 18:10

Sulthan


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 reference

like image 32
Arco Avatar answered Oct 02 '22 18:10

Arco