【问题标题】:Completion with for-loop in Swift在 Swift 中使用 for 循环完成
【发布时间】:2018-07-01 08:20:53
【问题描述】:

我正在尝试使用 Firebase 编写一个函数,该函数允许知道是否使用了用户名。

for username in dict.values {
               if username as? String == self.usernameText.text! {
                  appDelegate.visualReturnBottom(message: "Username already taken.", color: brandBlue, backgroundColor: UIColor.white)
                  return
               }
}

问题是,如果不使用用户名,我想更改视图控制器。为此,我必须等待循环结束,我真的不知道我该怎么做。

我想添加这部分代码“如果循环结束...:”

let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "InscriptionSecondVC") as! Inscription2TableViewController

self.navigationController?.pushViewController(nextVC, animated: true)

【问题讨论】:

  • 只需在循环“下方”写两行?
  • 补充@Sweeper 的答案;在主队列中编写 UI 更改代码。

标签: ios swift loops firebase swift3


【解决方案1】:

如果您要检查用户名匹配的值字典,则必须等到循环完成。没有其他方法可以执行该检查。由于您的代码目前已构成,这应该可以工作。

for username in dict.values {
    if username as? String == self.usernameText.text! {
        appDelegate.visualReturnBottom(message: "Username already taken.", color: brandBlue, backgroundColor: UIColor.white)
            return
       }
}

// if the username is already taken, you will never reach this point.
let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "InscriptionSecondVC") as! Inscription2TableViewController

self.navigationController?.pushViewController(nextVC, animated: true)

至于Dan's answer,我同意,你应该考虑重组你的数据。这只是对您的具体问题的回答。

【讨论】:

  • 干杯@dstepan +1
  • 哦,好吧,我不确定是否在循环结束之后调用了 for 循环之后的行。谢谢!
【解决方案2】:

您可能希望充分利用 Firebase 的功能并稍微不同地构建您的数据库,以帮助您更有效地执行此操作。

您可能想尝试创建一个用户名节点并像这样构造它。当用户使用用户名注册时,您可以将他们的用户名添加为 KEY,将 VALUE 添加为 1。这样您就可以简单地检查用户名树是否包含特定的用户名:

usernames:
- Bob: 1
- Dan: 1
- Billy: 1

这使您可以简单地检查用户名树是否具有 usernameText.text 输出的子节点,如下所示:

func handleCheckUsername() {
    guard let username = self.usernameText.text else { return }
    let reference = Database.database().reference()
    reference.child("usernames").observeSingleEvent(of: .value, with: { (snapshot) in

        if snapshot.hasChild(username) {
            print("Username is taken.")
        } else {
            print("Username isn't taken.")
        }

    }, withCancel: nil)
}

【讨论】:

  • 这是我所做的,但我不得不更改此架构,因为 %username* 无法处理点或 $ 例如...:/
猜你喜欢
  • 1970-01-01
  • 2020-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多