ios weak和unown,在闭包参数Swift中添加[unown self]

I have a function with a completion handler, returning one parameter or more.

In a client, when executing a completion handler, I'd like to have an unowned reference to self, as well as having access to the parameter passed.

Here is the Playground example illustrating the issue and the goal I'm trying to achieve.

import UIKit

struct Struct {

func function(completion: (String) -> ()) {

completion("Boom!")

}

func noArgumentsFunction(completion: () -> Void) {

completion()

}

}

class Class2 {

func execute() {

Struct().noArgumentsFunction { [unowned self] in

//...

}

Struct().function { (string) in // Need [unowned self] here

//...

}

}

}

解决方案

As I said in my comment

Struct().function { [unowned self] (string) in

//your code here

}

Capture list and closure parameters that should be the order in closures more info from Apple Documentation

Defining a Capture List

Each item in a capture list is a pairing of

the weak or unowned keyword with a reference to a class instance (such

as self) or a variable initialized with some value (such as delegate =

self.delegate!). These pairings are written within a pair of square

braces, separated by commas.

Place the capture list before a closure’s parameter list and return

type if they are provided:

lazy var someClosure: (Int, String) -> String = {

[unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in

// closure body goes here

}

If a closure does not specify a parameter list or return type because

they can be inferred from

context, place the capture list at the very start of the closure,

followed by the in keyword:

lazy var someClosure: () -> String = {

[unowned self, weak delegate = self.delegate!] in

// closure body goes here

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值