mbrgm
mbrgm

Reputation: 73

Passing struct literal to ObjC method

During a talk at the @Scale 2014 conference (around 32:30), Facebook presented their implementation of a declarative UI approach. The slides for a more detailed version of the talk can be found here.

Basically they presented a function call like this (I made my own simplified example from the example in the talk):

[CPInsetComponent
  newWithStyle:{
    .margin = 15
  }
];

My question is: Is this valid ObjC code? I tried to implement this myself

typedef struct {
  uint margin;
} CPInsetComponentStyle;


@interface CPInsetComponent : NSObject

+ (SomeOtherStruct) newWithStyle:(CPInsetComponentStyle)style;

@end

but I still get an "expected expression" error on the newWithStyle:{ line. Could you give me a hint how the method declaration would look like?

Upvotes: 1

Views: 417

Answers (2)

Paul.s
Paul.s

Reputation: 38728

The compiler probably doesn't know if your literal struct declaration is of the correct type. For compound literals you need to provide the type in parenthesis followed by a brace-enclosed list of initializers.

[CPInsetComponent newWithStyle:(CPInsetComponentStyle){
  .margin = 15
}];

Upvotes: 2

No, that's not valid Objective-C code. A C99 compound literal of struct type looks like this:

(TheStructType) { .field1 = initializer1, .field2 = initializer2 }

where the field designators are optional.

I can imagine that the code they were presenting was actually Objective-C++. In C++11, the compiler can insert implicit calls to constructors taking an initializer list if certain conditions are met; hence, often you can pass just an initializer list to a function.

Upvotes: 3

Related Questions