Search code examples
swiftstringemailstructsubclass

String subclass workaround in Swift


In my app I work with various structs that should really be basically just String subclasses, but String is a struct itself so it’s not possible to subclass it. For example, I have an Email object with a single address variable and then computed variables such as isValid or functions such as compose(). The point is that it seems ridiculous to access the actual email address through the address property when the whole object should, in fact, be the address.

So what is the proper way to create an Email object? Is this the only way? Or is there a way around subclassing string so that my email struct is actually a string just with some email-specific functions?


Solution

  • I would use something like this:

    import Foundation
    
    struct EmailAddress {
        let stringValue: String
    
        static func isValidEmailAddress(_ s: String) -> Bool {
            //implement me
            return true
        }
    
        init?(fromString s: String) {
            guard EmailAddress.isValidEmailAddress(s) else { return nil }
            self.stringValue = s
        }
    
        var localPart: String {
            return stringValue.components(separatedBy: "@").first!
        }
    
        var domain: String {
            return stringValue.components(separatedBy: "@").last!
        }
    
        // expose other functions that make sense to e-mail addresses.
        // importantly, this doesn't expose *all* String methods,
        // most of which wouldn't make sense in the context of a String
    }