I'm very new to the Swift language.
I wanted to declare an inline function just like in C++ so my func
declaration looks like this:
func MyFunction(param: Int) -> Int { ... }
and I want to do something like this:
inline func MyFunction(param: Int) -> Int { ... }
I tried to search on the web but I didn't find anything relevant maybe there is no inline
keyword but maybe there is another way to inline the function in Swift.
To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line.
Even though the compiler can make its own inlining decisions, the @inline attribute can be used in Swift to force its decision. It can be used in two ways: @inline(__always) : Signals the compiler to always inline the method, if possible. @inline(never) : Signals the compiler to never inline the method.
An equivalent way to declare an inline member function is to either declare it in the class with the inline keyword (and define the function outside of its class) or to define it outside of the class declaration using the inline keyword.
Any function, with the exception of main , can be declared or defined as inline with the inline function specifier. Static local variables are not allowed to be defined within the body of an inline function. C++ functions implemented inside of a class declaration are automatically defined inline.
Swift 1.2 will include the @inline
attribute, with never
and __always
as parameters. For more info, see here.
As stated before, you rarely need to declare a function explicitly as @inline(__always)
because Swift is fairly smart as to when to inline a function. Not having a function inlined, however, can be necessary in some code.
Edit: Swift 5 added the @inlinable
attribute. Make sure you read up about it, as there may be a couple of gotchas that might make in unusable. It's also only for functions/methods declared public
, so it's meant for those wanting to expose inline stuff for those that link to your library.
All credit to the answer, just summarizing the information from the link.
To make a function inline just add @inline(__always)
before the function:
@inline(__always) func myFunction() { }
However, it's worth considering and learning about the different possibilities. There are three possible ways to inline:
@inline(__always)
before the function. Use "if your function is rather small and you would prefer your app ran faster."@inline(never)
before the function. Use "if your function is quite long and you want to avoid increasing your code segment size." If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With