@propertyWrapper: Encoding Strings to Valid URL Characters

@propertyWrapper: Encoding Strings to Valid URL Characters

With this @propertyWrapper code snippet you will be able to wrap String values into wrapped values of url safe characters.

Porperty wrappers serve as a new type to wrap properties and add additional logic if needed. It's part of Swift since version 5.1 and can be useful to validate values woth a set of rules or tranform values to match certain requirements etc.

As a simple example, you might want to ensure that String is using upper case, for example to correctly describe the abbreviation of federal states in the U.S. like California (CA) or New York (NY) or you could ensure that a url provided as a String includes only valid url characters.

The property wrapper can be defined as a class with a private(set) property value that then returns a wrappedValue by transforming the internal value to valid url characters, such as this:

import Foundation

@propertyWrapper
class URLEncode {
    
    private(set) var value: String = ""
    
    var wrappedValue: String {
        get { value }
        set {
            if let url = newValue.addingPercentEncoding(withAllowedCharacters: .urlUserAllowed) {
                self.value = url
            }
        }
    }
    
}

Then, whenever defining a resource, for example a url to fetch weather data from the openweathermap.org API, the endpoint url could be constructed with input that may include spaces etc. that would automatically be transformed to a valid url with the propertywapper @URLEncode as shown below.

struct Resource {
    
    @URLEncode
    var city: String
    var url: String {
        
        "https://samples.openweathermap.org/data/2.5/weather?q=\(city)&appid=YOUR-API-KEY"
    }
    
    init(city: String) {
        self.city = city
    }
}

var resource = Resource(city: "Los Angeles")
print(resource.city)
print(resource.url)

There are many other cool things you can do with @porpertyWrapper. For more conclusive coverage, consider "Property Wrappers in Swift explained with code examples" by Antoine van der Lee or "Property wrappers in Swift" by John Sundell. Both provide an excellent overview.