[swift-users] Generics question - can you handle both optional and non-optional args with the same function?

Kenny Leung kenny_leung at pobox.com
Thu Jan 11 19:55:40 CST 2018


Hi All.

I’m trying to write a utility method that is kind of the opposite of “x ?? y”, which means “x != nil ?  x : y”. I want “x != nil ? f(x) : nil” This is not difficult to write, but if you have "f(x)->z" and "g(x)->z?", I seem to need two versions of the function in order to handle it. Is there any way to do this with only one function?

public func fnil<XType,RetType> (
    _ x:XType?,
    _ f:(XType)->RetType
    )
    -> RetType?
{
    if let x = x {
        return f(x)
    } else {
        return nil
    }
}

public func fnil<XType,RetType> (
    _ x:XType?,
    _ g:(XType)->RetType?
    )
    -> RetType?
{
    if let x = x {
        return g(x)
    } else {
        return nil
    }
}

    private func f(_ x:Int) -> Int {
        return x
    }
    
    private func g(_ x:Int) -> Int? {
        if x == 5 {
            return nil
        } else {
            return x
        }
    }
    
    func testFnil() {
        XCTAssertNil(fnil(nil, {f($0)}))
        XCTAssertEqual(7, fnil(7,{f($0)}))
        
        XCTAssertNil(fnil(nil, {g($0)}))
        XCTAssertEqual(7, fnil(7, {g($0)}))
        XCTAssertNil(fnil(5, {g($0)}))
    }

Thanks!

-Kenny

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20180111/1ab616de/attachment.html>


More information about the swift-users mailing list