为什么Xcode会显示警告'永远不会被执行'在我的'如果'条款?

时间:2016-06-18 09:33:02

标签: swift if-statement compiler-warnings

如果没有要加载的数据,或者正在提取数据等,我想在我的tableview背景上显示注释/标签。

我无法在这里看到我做错了什么。 Xcode正在显示警告&#34;永远不会被执行&#34;在这行代码上:if mostUpTodateNewsItemsFromRealm?.count < 1 {

这是方法。

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    // create a lable ready to display
    let statusLabel: UILabel = UILabel(frame: CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height))
    statusLabel.textColor = globalTintColor
    statusLabel.textAlignment = NSTextAlignment.Center
    self.tableView.backgroundView = statusLabel
    self.tableView.backgroundView?.backgroundColor = colourOfAllPickerBackgrounds

    // 1) Check if we have tried to fetch news
    if NSUserDefaults.standardUserDefaults().valueForKey("haveTriedToFetchNewsForThisChurch") as! Bool == false {
        statusLabel.text = "Busy loading news..."

    } else {
        // If have tried to fetch news items = true
        // 2) check church has channels
        let numberOfChannelsSubscribedToIs = 0
        if let upToDateSubsInfo = upToDateChannelAndSubsInfo {
            let numberOfChannelsSubscribedToIs = 0
            for subInfo in upToDateSubsInfo {
                if subInfo.subscribed == true {
                    numberOfChannelsSubscribedToIs + 1
                }
            }
        }
        if numberOfChannelsSubscribedToIs < 1 {
            // if no channels
            // show messsage saying you aren't subscribed to any channels.
            statusLabel.text = "Your church hasn't setup any news channels yet."

        } else {

            // 3) if we have tried to fetch news AND the church DOES have channels
            // check if we have any news items to show
            if mostUpTodateNewsItemsFromRealm?.count < 1 {

                // If no news items
                statusLabel.text = "Your church hasn't broadcast and news yet."
            } else {
                // if have tried to fetch AND church has channels AND there ARE news items
                // remove the background image so doesn't show when items load.
                self.tableView.backgroundView = nil
            }
        }
    }
    // in all circumstances there will be one section
    return 1
}

1 个答案:

答案 0 :(得分:1)

您的代码首先创建了一个常量:

let numberOfChannelsSubscribedToIs = 0

然后检查它是否小于1:

if numberOfChannelsSubscribedToIs < 1

因为它是常数,所以永远不会改变。这意味着将始终执行if子句。因此,永远不会执行else子句。

首先,您需要创建这个常量变量:

var numberOfChannelsSubscribedToIs = 0

然后改变这个:

if subInfo.subscribed == true {
    numberOfChannelsSubscribedToIs + 1
}

到此:

if subInfo.subscribed == true {
    numberOfChannelsSubscribedToIs += 1
}

这样,numberOFChannelSubscribedToIs可以是0以外的某个数字。可以执行else子句。

varlet非常不同!

相关问题