Determine if Any.Type is Optional

前端 未结 4 1678
滥情空心
滥情空心 2020-12-05 19:55

I’m trying to determine if a given type t (Any.Type) is an optional type, I’m using this test

t is Optional.Type
         


        
4条回答
  •  感情败类
    2020-12-05 20:02

    You can do something like this:

    extension Mirror {
        static func isOptional(any: Any) -> Bool {
            guard let style = Mirror(reflecting: any).displayStyle,
                style == .optional else { return false }
            return true
        }
    }
    

    Usage:

    XCTAssertTrue(Mirror.isOptional(any: Optional(1)))
    

    Or if you need to cast from Any to Optional

    protocol _Optional {
        var isNil: Bool { get }
    }
    
    extension Optional: _Optional {
        var isNil: Bool { return self == nil }
    }
    
    func isNil (_ input: Any) -> Bool {
        return (input as? _Optional)?.isNil ?? false
    }
    

    Usage:

    isNil(nil as String?) // true
    isNil("") // false
    

提交回复
热议问题