thecloud_of_unknowing thecloud_of_unknowing - 5 months ago 12
Swift Question

Why does Xcode show warning 'Will never be executed' on my 'if' clause?

I want to show a note/label on my tableview background when/if there is no data to load, or data is being fetched etc.

I can't see what am I doing wrong here. Xcode is showing a warning "Will never be executed" on this line of code:

if mostUpTodateNewsItemsFromRealm?.count < 1 {


Here is the method.

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
}

Answer

Your code first created a constant:

let numberOfChannelsSubscribedToIs = 0

And then you check whether it is less than 1:

if numberOfChannelsSubscribedToIs < 1

Since it is a constant, it will never change. This means that the if clause will always be executed. Thus, the else clause will never be executed.

So first you need to make this constant variable:

var numberOfChannelsSubscribedToIs = 0

Then just change this:

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

to this:

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

This way, numberOFChannelSubscribedToIs can be some number other than 0. And the else clause can be executed.

var and let are very different!