Optional struct argument in Objective-C++

Viewed 48

I have to hack on an Objective-C++ project and I am trying to figure out how optionals work there. What's the analogous of std::optional there?

Simple example:

- (void)foo:(CGSize)first
     second:(nullable CGSize*)second;

I can now pass nil if I want to omit second.

However, I cannot figure out how to construct a pointer to CGSize to pass it to foo.

1 Answers
  1. If you're using Objective-C++ throughout (the implementation and the consumer of the API are both Objective-C++, not Objective-C) you can just use std::optional:
- (void)foo:(CGSize)first
     second:(std::optional<CGSize>)second;
  1. If your method needs to be callable from Objective-C, you can use a pointer, as you indeed have in your code snippet. However, for non-object types (non-@interface, non-id, non-@protocol) you use NULL instead of nil in Objective-C, much as you do in C. (You can interchangeably use nullptr instead of NULL in Objective-C++, with the former providing all the advantages it also gives in pure C++.)
Related