Optional extension

We were trying to work out how to add an extension method to String? optional type that combines the nil check and empty string test.

We came up with two methods which work in an XCode playground, below. Neither of these compile in Silver - for the first method it whinges about the where clause in the extension, and for the second it “Cannot infer enum type from context”

This isn’t high priority at all, its just tinkering really, but shows up some more incompatibilities.


// First method, using a where in the extension. 
// Inspired from http://stackoverflow.com/a/33717847/2102158

// Need a protocol to make the where clause work
public protocol StringType { var get: String { get } }
extension String: StringType { public var get: String { return self } }

public extension Optional where Wrapped: StringType
{
    
    public var isEmpty: Bool
    {
        if let s = self
        {
            return s.get.isEmpty
        }
        return true
    }
    
}


/* Second method, extend optional and check type. This is less ideal as it applies the method to every optional type

extension Optional
{
    public var isEmpty: Bool
    {
        switch(self)
        {
        case .None:
            return false
        case .Some(let value):
            if let str = value as? String
            {
                return str.isEmpty
            }
            return false
        }
        
    }
}
*/
let s: String? = nil
assert( s.isEmpty )


let s2: String? = "hello"
assert( !s2.isEmpty )

let s3: String? = ""
assert( s3.isEmpty )

let s4: String = "hello"
assert( !s4.isEmpty )

let s5: String = ""
s5.isEmpty
assert( s5.isEmpty )