12

I have recently been introduced to swift.

A question, when to use CGPoint and when shall I use CGPointMake ?

I have interchanged these two statements and they both returned the same result

 self.anchorPoint  = CGPointMake(0.5, 0.5)

 self.anchorPoint  = CGPoint(0.5, 0.5)

Thanks

rmaddy
  • 314,917
  • 42
  • 532
  • 579
user2725255
  • 121
  • 1
  • 1
  • 3

2 Answers2

18

Every struct in Swift gets an automatically created member-wise initializer. So, because struct CGPoint exists with members x and y, you can do:

 self.anchorPoint  = CGPoint(x: 0.5, y: 0.5)

(Note that you can't actually do CGPoint(0.5, 0.5) -- that gets a compile error because initializers require labels for all parameters, except where otherwise declared.)

In Swift 1.x-2.x, CGPointMake was a function imported from the C version of this API. In Swift 3, the initializer form is the only way to create a CGPoint -- it's one of the changes to make CoreGraphics much more Swifty.

rickster
  • 124,678
  • 26
  • 272
  • 326
  • *"because C doesn't have member-wise initializers like Swift does"* - not quite, you have a ["compound literal"](https://gcc.gnu.org/onlinedocs/gcc/Compound-Literals.html) `self.anchorpoint = (CGPoint){ 0.5, 0.5 };`, but that is relatively new. – Martin R Aug 21 '14 at 18:10
  • C99 also has the `{.x = 0.5, .y = 0.5}` syntax. – jtbandes Aug 21 '14 at 18:14
  • @jtbandes: Yes, but that is (if I remember correctly) a "designated initializer". You can use it to define and init a struct `CGPoint p = {.x = 0.5, .y = 0.5}`, but not as an expression in an assignment. `self.anchorpoint = {.x = 0.5, .y = 0.5}` does not compile. – Martin R Aug 21 '14 at 18:15
  • It does if you cast it! – jtbandes Aug 21 '14 at 22:16
  • @rickster The OP linked here from a tutorial saying he didn't really understand your answer. Would you consider editing to remove terminology which relies on the assumption that the reader knows anything about C / swift. For example, what do you meant by "struct" and "member-wise initializers"? These are terms I'm not familiar with, and expect the OP isn't familiar with either. – Relequestual Nov 12 '15 at 13:50
3

When you cmd-click on the type Xcode opens the file with the definition.

CGPoint is a struct:

struct CGPoint {
    var x: CGFloat
    var y: CGFloat
}

and CGPointMake is just a function which creates a CGPoint and returns it:

func CGPointMake(x: CGFloat, y: CGFloat) -> CGPoint
zisoft
  • 22,770
  • 10
  • 62
  • 73