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.
How to create an inline anonymous function, for immediate use in a function call?
func doMath
– as you defined it – takes a closure as the first argument,
and two integers as second and third argument. Therefore you call it as
doMath({
(m1:Int, m2:Int) -> () in
print(m1 * m2)
}, 5, 8)
or with shorthand parameters:
doMath({ print($0 * $1) }, 5, 8)
If you change the function definition to take the closure as the last
parameter
func doMath(_ i1: Int, _ i2: Int, _ f:(_ i1 : Int, _ i2 : Int) -> ()) {
print("doing Math")
f(i1, i2)
}
then you would call it as
doMath(5, 8, { print($0 * $1) })
or, using the “trailing closure” syntax:
doMath(5, 8) { print($0 * $1) }
Can I bridge C inline functions to Swift?
The compiler will do what it wants but generally the answer is yes. This is part of why the atomics libraries and math shims that go down to C use header only inlined modules. So at least in release builds it can be fully optimized.
See this for example https://github.com/apple/swift-numerics/tree/main/Sources/_NumericsShims
Passing inline function definition as input parameter to a function
Think about the difference between declaring an object and then using it:
var a = 100
abs(a)
vs using it directly:
abs(100)
Same difference applies between declaring then using a function:
func talk(x: String) { return x + " is talking" }
doThis(talk)
vs using it directly:
doThis( { x: String -> return x + " is talking" } )
Writing
doThis( func talk(x: String) { return x + " is talking" } )
is like writing
abs(var a = 100)
which doesn't make sense.
Swift define and call inline closure directly
> true == a()
compares true
with the result of calling the closure a
(with an empty argument list). You can do the same inline, but you must still call the closure:
> true == { ()-> Bool in return true }()
$R0: Bool = true
Note that a test for equality with true
is always redundant, so this expression is identical to
{ ()-> Bool in return true }()
how can i use `#function` symbol in a `inline` function?
If your intention is to print the name of the function which callslog()
, then you should pass it as default argument (which is evaluated
in the context of the caller), as demonstrated
in Building assert()
in Swift, Part 2: __FILE__
and __LINE__
in the Swift blog.
Example:
@inline(__always) func log(_ message: String, callingFunction: String = #function) {
print("\(callingFunction): \(message)")
}
func a() { log("Hello world") }
func b() { log("Foo") }
func c() { log("Bar") }
a() // a(): Hello world
b() // b(): Foo
c() // c(): Bar
This works regardless of whether the log
function is inlined or not.
(Inlining does not change the semantics of a program. In particular,
it does not mean that the source code of func log
is included from
the source code of func a()
and compiled as a single function.)
Swift callback inline function usage
There are several ways to declare or use closures. The simplest one you're looking for is probably:
{ status_code, data in
println(status_code)
}
This needs to be used in such a way that the compiler can infer the type of status_code
, data
, and determine that there should be no return value. For instance, you can pass it as a function parameter (what you want), or assign it to a variable with appropriate type hints.
Swift setting variable inline or in function?
First of all, you have two fundamentally different types in your two examples. In the first example, the type is an implicitly unwrapped optional String
(i.e., String!
), which means it can accept the nil
value. In the second example, it is just String
. If the value does not need to be nil
assignable, the second option is better.
With regard to your actual question. I would say the second option is preferable, as you initialize the value earlier and there is no chance that you will use it before it is initialized. This would be equivalently good to declaring the type as String
and deferring the initialization to an init
method.
The viewDidLoad
method is only useful for UIViewController
instances, and doesn't get invoked until the view is loaded (which typically is during presentation). Waiting to initialize a value until then is probably not preferred and wouldn't be useful in objects that don't subclass UIViewController
.
Can I set variable value with function result inline in Swift?
Try this:
lblTitle.text = {
switch tag {
case 0:
return "title0"
default:
return "DefaultTitle"
}
}()
Just wanted to add to this.
You can also create variables this way but you will need to add type information like this...
// If you don't provide type then the closure is ambiguous
let someLabel: UILabel = {
let l = UILabel()
l.font = .systemFont(ofSize: 20)
l.textColor = .red
l.text = "Hello, world!"
return l
}()
Related Topics
Cannot Load Underlying Module for Xctest
What Is a 'Non-Nominal Type' in Swift
How to Split an Int to Its Individual Digits
Swiftui: How to Present View When Clicking on a Button
How to Assign an Optional Binding Parameter in Swiftui
Segue from a Slpagingviewswift Vc and Dismiss the Destination Vc to Return
Ondelete Causing Nsrangeexception
Compare App Versions After Update Using Decimals Like 2.5.2
What Are 'Get' and 'Set' in Swift
Select Multiple Rows in Tableview and Tick the Selected Ones
Lazy Loading Properties in Swift
Today Extension Failed to Inherit Coremedia Permissions From