Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NULL parameter in Swift

Tags:

swift

In Objective-C, we can declare a function like this:

- (void)getRect:(CGRect *)aRectRef bRect:(CGRect *)bRectRef
{
    if (aRectRef) *aRectRef = CGRectZero
    if (bRectRef) *bRectRef = CGRectZero
}

and pass NULL to the function:

CGRect rect;
[self getRect:NULL bRect:rect]

There isn't NULL in Swift. I can't use nil as inout param directly either:

func getRect(aRect aRectRef: inout CGRect?, bRect bRectRef: inout CGRect?) -> Void {
    ...
}
self.getRect(&nil, bRect: rect) // <- ERROR

I must define a variable with nil value and pass it to the function, even though I don't need the variable totally.

How to pass nil to the function?

UPDATE:

null / nil in swift language just explained nil in Swift.

Swift optional inout parameters and nil explained how to define a variable with nil value and pass it as inout parameter.

I want to know there is a way to pass nil directly like &nil to function or not.

like image 699
Vayn Avatar asked Mar 09 '26 00:03

Vayn


1 Answers

Your Objective-C method has nullable pointers as parameters, in Swift 3 that would be an optional UnsafeMutablePointer:

func getRect(aRectRef: UnsafeMutablePointer<CGRect>?, bRectRef: UnsafeMutablePointer<CGRect>?) {
    if let aRectPtr = aRectRef {
        aRectPtr.pointee = CGRect(x: 1, y: 2, width: 3, height: 4)
    }
    if let bRectPtr = bRectRef {
        bRectPtr.pointee = CGRect(x: 5, y: 6, width: 7, height: 8)
    }
}

var rect = CGRect.zero
getRect(aRectRef: &rect, bRectRef: nil)
print(rect) // (1.0, 2.0, 3.0, 4.0)

So you can pass nil as an argument. What you can not do (in contrast to Objective-C) is to pass the address of an uninitialized variable, rect must be initialized here.

The same can be written more compactly as

func getRect(aRectRef: UnsafeMutablePointer<CGRect>?, bRectRef: UnsafeMutablePointer<CGRect>?) {

    aRectRef.map { $0.pointee = CGRect(x: 1, y: 2, width: 3, height: 4) }
    bRectRef.map { $0.pointee = CGRect(x: 5, y: 6, width: 7, height: 8) }
}
like image 175
Martin R Avatar answered Mar 11 '26 13:03

Martin R