mirror of
https://github.com/apple/swift.git
synced 2025-12-14 20:36:38 +01:00
Introduce callables: values of types that declare `func callAsFunction`
methods can be called like functions. The call syntax is shorthand for
applying `func callAsFunction` methods.
```swift
struct Adder {
var base: Int
func callAsFunction(_ x: Int) -> Int {
return x + base
}
}
var adder = Adder(base: 3)
adder(10) // desugars to `adder.callAsFunction(10)`
```
`func callAsFunction` argument labels are required at call sites.
Multiple `func callAsFunction` methods on a single type are supported.
`mutating func callAsFunction` is supported.
SR-11378 tracks improving `callAsFunction` diagnostics.
15 lines
447 B
Swift
15 lines
447 B
Swift
// RUN: %empty-directory(%t)
|
|
// RUN: %target-swift-frontend -emit-module -primary-file %S/Inputs/call_as_function_other_module.swift -emit-module-path %t/call_as_function_other_module.swiftmodule
|
|
// RUN: %target-swift-frontend -typecheck -I %t -primary-file %s -verify
|
|
|
|
import call_as_function_other_module
|
|
|
|
func testLayer<L: Layer>(_ layer: L) -> Float {
|
|
return layer(1)
|
|
}
|
|
|
|
func testDense() -> Float {
|
|
let dense = Dense()
|
|
return dense(1)
|
|
}
|