有没有办法在 Swift 中声明内联函数? [英] Is there a way to declare an inline function in Swift?

查看:160
本文介绍了有没有办法在 Swift 中声明内联函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Swift 语言非常陌生.

我想声明一个 inline 函数,就像在 C++ 中一样所以我的 func 声明如下所示:

func MyFunction(param: Int) ->整数{...}

我想做这样的事情:

inline func MyFunction(param: Int) ->整数{...}

我尝试在网上搜索,但没有找到任何相关内容,也许没有 inline 关键字,但也许有另一种方法可以在 Swift 中内联该函数.

解决方案

Swift 1.2 将包含 @inline 属性,带有 never__always> 作为参数.有关详细信息,请参阅此处.>

如前所述,您很少需要将函数显式声明为 @inline(__always),因为 Swift 在何时内联函数方面相当聪明.但是,在某些代码中可能需要不内联函数.

Swift 5 添加了 @inlinable 属性.确保你阅读了它,因为可能有几个问题可能会导致无法使用.它也仅适用于声明为 public 的函数/方法,因此它适用于那些希望为链接到您的库的那些公开内联内容的人.

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.

解决方案

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.

这篇关于有没有办法在 Swift 中声明内联函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆