Search code examples
swiftdouble

What is the difference between function and function(_:) in Swift?


I've recently used flatMap to map String? to Double? in Swift. Calling:

optionalString.flatMap(Double.init)

and

optionalString.flatMap(Double.init(_:))

produces the same result. I have two questions:

  • Is there a difference between Double.init and Double.init(_:)?
  • I did not think that you can use function signatures in real Swift code. What are some other examples where you can use these?

Solution

  • No, there is no difference between Double.init and Double.init(_:). These are called first class functions in Swift. For example:

    extension UIView {
        func addSubviews(_ views: UIView...) {
        views.forEach(addSubview)
      }
    }
    

    More info: First class functions in Swift

    Edit: There is a difference between Double.init and Double.init(_:). ( check comments )