0

I found this in some open source code.

I am familiar with map(), but not the CGFloat.init(_:)) part.

The Swift code is as follows:

if let array = propertyListValue as? [Int], array.count == 3 || array.count == 4 {
        let floats = array.map(CGFloat.init(_:))
}

Not sure what to look for in docs. I know what _ name : Type means in a function declaration... but just confused by this use case.

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
clearlight
  • 12,255
  • 11
  • 57
  • 75

1 Answers1

2

map takes one argument, a function that accepts an argument of the sequence element type and returns any type. CGFloat.init is the name of (technically a reference to) just such a function.

Perhaps you think of map as taking a "closure", and indeed you could equivalently have said

map { CGFloat($0) }

here; but that's in fact exactly the same sort of function — it's just that instead of the function's name (reference) you're supplying its body.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    clearflight said that they already understand what `map` is. They are asking about the `_:` part of the statement. – William Fleetwood Aug 28 '22 at 04:22
  • So I assume that passing the signature for the parameters is similar to #selector(function(_:)) where you're saying here is my func ref, and here is how it should be called. Got it. Ty – clearlight Aug 28 '22 at 05:50
  • My explanation of function reference _syntax_ (if that's in fact what's not understood) is here: https://stackoverflow.com/a/35658335/341994 – matt Aug 28 '22 at 10:37