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
}
NULL
CGRect rect;
[self getRect:NULL bRect:rect]
NULL
nil
func getRect(aRect aRectRef: inout CGRect?, bRect bRectRef: inout CGRect?) -> Void {
...
}
self.getRect(&nil, bRect: rect) // <- ERROR
nil
nil
&nil
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) }
}