Is there a way to declare an inline function in Swift?

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.

Swift-5 added the @inlinable attribute, which helps ensuring that library/framework stuff are inlineable for those that link to your library. Make sure you read up about it, as there may be a couple of gotchas that might make it unusable. It's also only for functions/methods declared public, as it's meant for libraries wanting to expose inline stuff.


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:

  • sometimes - will make sure to sometimes inline the function. This is the default behavior, you don't have to do anything! Swift compiler might automatically inline functions as an optimization.
  • always - will make sure to always inline the function. Achieve this behavior by adding @inline(__always) before the function. Use "if your function is rather small and you would prefer your app ran faster."
  • never - will make sure to never inline the function. This can be achieved by adding @inline(never) before the function. Use "if your function is quite long and you want to avoid increasing your code segment size."