Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why {} works for C Structs but not for properties

I came across something the other day for setting the value of C Structs by using curly braces and it works great but I'm wondering why exactly can I not use it for setting the value of properties?

//This works:
CGPoint pt = {10, 20};
CGRect rct = {0, 5, 50, 50};

//But this doesn't:
self.frame = {0, 5, 50, 50};
imageview.center = {100, 120};

The compiler error is "expected expression"

I think I know why this doesn't work, but I would like a more thorough explanation.

like image 226
daveMac Avatar asked Dec 28 '22 00:12

daveMac


2 Answers

The first lines combine declaration and initialisation of variables. The compiler infers the type of the right expression from the type of the left expression, and distributes the numbers in the struct slots as expected.

The last lines, however, are not initialisations. Now the compiler won't infer anything. As a consequence, the compiler doesn't know how it should interpret the stuff on the right. What is its type, how to layout those numbers in memory ? The compiler won't assume its CGrect or CGPoint, and you must help him with an explicit cast (CGRect){0,5,50,50} which gives him the missing information.

like image 92
Gwendal Roué Avatar answered Dec 30 '22 10:12

Gwendal Roué


This should work:

self.frame = (CGRect){0, 5, 50, 50};
imageview.center = (CGPoint){100, 120};
like image 32
DrummerB Avatar answered Dec 30 '22 09:12

DrummerB