【问题标题】:Return missing from this function?从这个函数返回丢失?
【发布时间】:2020-07-02 16:25:06
【问题描述】:

我收到此错误“Missing return in a function expected to return 'NSAttributedString?'”

有人可以帮忙吗?我正在为这件事打败我的小脑袋——容易犯白痴错误。我输入了“dummyString”行以确保有回报,但没有运气。

TIA

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {

    let dummyString = "Dummy String"


    if component == 1 {
        return NSAttributedString(string: denomArray[row], attributes: [NSAttributedString.Key.foregroundColor: UIColor.yellow])

    }else if component == 0 {
        if issuerArray [row] == "US" {
            return NSAttributedString(string: self.issuerArray[row], attributes: [NSAttributedString.Key.foregroundColor: BaseViewController.Flag.us.themeColor])
        }
        if issuerArray [row] == "Canada" {
            return NSAttributedString(string: self.issuerArray[row], attributes: [NSAttributedString.Key.foregroundColor: BaseViewController.Flag.canada.themeColor])
        }

    }else{
        return NSAttributedString(string: dummyString, attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])

    }
}

【问题讨论】:

    标签: ios swift if-statement return


    【解决方案1】:

    问题在于 if component == 0 块的构造。如果这个国家既不是美国也不是加拿大,那么就没有回报。您可能知道该行只能包含这两个值之一,但编译器不会。

    最简单的解决方法是使默认的return 成为无条件的。这样,如果之前没有执行过return,您将返回默认值。

    func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    
        let dummyString = "Dummy String"
    
        if component == 1 {
            return NSAttributedString(string: denomArray[row], attributes: [NSAttributedString.Key.foregroundColor: UIColor.yellow])
    
        } else if component == 0 {
            if issuerArray [row] == "US" {
                return NSAttributedString(string: self.issuerArray[row], attributes: [NSAttributedString.Key.foregroundColor: BaseViewController.Flag.us.themeColor])
            }
            if issuerArray [row] == "Canada" {
                return NSAttributedString(string: self.issuerArray[row], attributes: [NSAttributedString.Key.foregroundColor: BaseViewController.Flag.canada.themeColor])
            }
        }
        return NSAttributedString(string: dummyString, attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
    
    }
    

    【讨论】:

    • 解决了这个问题,也给我上了宝贵的一课。非常感谢,好先生!
    【解决方案2】:

    您只需在最后一行上方添加return nil

    【讨论】:

      猜你喜欢
      • 2014-04-12
      • 2013-03-18
      • 1970-01-01
      • 2018-02-16
      • 2020-03-06
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      相关资源
      最近更新 更多