【问题标题】:what does the line self = self do in swift这条线 self = self 迅速做什么
【发布时间】:2020-04-16 07:50:44
【问题描述】:

有人可以向我解释一下这段代码中 self = self 的目的是什么吗?

// Keep the reference to the interface :
private var guidedItfRef: Ref<GuidedPilotingItf>?
private var goUp: Bool
...
guidedItfRef = provider.getPilotingItf(PilotingItfs.guided) { [weak self] guidedItf in
    if let guidedItf = guidedItf, let self = self, guidedItf.currentDirective == nil {
        self.goUp = !self.goUp
        guidedItf.moveToRelativePosition(forwardComponent: 0, rightComponent: 0,
                downwardComponent: self.goUp ? 2.0 : -3.0 , headingRotation: 0)
    }
}

【问题讨论】:

  • 建议:如果使用较新版本的 Swift,请将 self.goUp = !self.goUp 替换为 self.goUp.toggle()

标签: swift


【解决方案1】:

当你在闭包中使用[weak self] 时,这将使self 成为可选的,因此你需要用let 解开它

, let self = self // rhs self is optional , `self` or let strongSelf = self

喜欢

var value:int?

解开选项 1

guard let value = value else { return } 
// use value which now is Int not int?

解开选项 2

if let value = value {  
   // use value which now is Int not int?
}

【讨论】:

  • 感谢您能提供更多细节,因为我是 swift 新手吗?
  • @bakalolo 我不知道我是否对您的理解不正确,但you also said you were new to Swift Jul 20 '15(4 年前)。
  • @George_E haha​​hahahahhahahahaha 好消息
  • @Sh_Khan 在看到他们的高分后,我点击了他们的个人资料(我链接的那篇帖子因其受欢迎程度而在他们的个人资料中显示为第一个)。他们实际上已经发布了一些关于 Swift 的旧帖子:p
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
  • 2019-04-21
相关资源
最近更新 更多