初始化需要“自我”的Swift属性作为一个论点 [英] Initializing Swift properties that require "self" as an argument

查看:113
本文介绍了初始化需要“自我”的Swift属性作为一个论点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Swift类,我希望看起来像这样:

I have a Swift class that I'd like to look something like this:

class UpdateManager {
  let timer: NSTimer

  init() {
    timer = NSTimer(timeInterval: 600, target: self, selector: "check", userInfo: nil, repeats: true)
  }

  func check() {
    // Do some stuff
  }
}

但是,Swift不喜欢我将 self 传递给 NSTimer 初始化程序。我在这里打破了一些模式吗?一个人应该如何完成这样的初始化?

However, Swift doesn't like the fact that I'm passing self to the NSTimer initializer. Am I breaking some pattern here? How is one supposed to accomplish initialization like this?

推荐答案

你找到了隐式展开可选


  • 您需要从 self > init ,在初始化 timer 之前。

  • 否则, timer 永远不会为零,所以你不必在 init 之外检查它。

  • You need to access self from init, before timer is initialized.
  • Otherwise, timer should never be nil, so you shouldn't have to check it outside of init.

所以,你应该声明让计时器:NSTimer!

这篇关于初始化需要“自我”的Swift属性作为一个论点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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