URL Escaped String (Swift)

February 16, 2019

When performing networking operations in iOS, it is useful to be able to url escape and convert strings into Data objects. Below is a helpful extension to achieve that functionality:

public extension String {
    var urlEscaped: String {
        return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    }
    
    var utf8Encoded: Data {
        return data(using: .utf8)!
    }
}

Usage:

print("Welcome to Gopher Labs".urlEscaped) //Welcome%20to%20Gopher%20Labs%0A