Created
December 4, 2024 13:46
-
-
Save emin-grbo/742ae4ac9268ec832cb4aff751bc2812 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension String { | |
/// Returns a percent-escaped string following RFC 3986 for a query string key or value. | |
/// | |
/// RFC 3986 states that the following characters are "reserved" characters. | |
/// | |
/// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" | |
/// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" | |
/// | |
/// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow | |
/// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" | |
/// should be percent-escaped in the query string. | |
/// | |
/// - returns: percent-escaped string. | |
public func encoded() -> String { | |
let generalDelimitersToEncode = ":#[]@" | |
let subDelimitersToEncode = "!$&'()*+,;=" | |
var allowedCharacterSet = CharacterSet.urlQueryAllowed | |
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") | |
return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? "" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment