如果声明导致'使用未解析的标识符'返回元组

时间:2015-10-28 00:14:02

标签: swift

下面显示的Swift(2)函数返回一个包含两个UIAlertAction实例cancelAction和doNotCancelAction的元组。在设置If语句代码块之前,实例按预期返回。

添加包含创建两个UIAlertAction实例的条件if代码块后,返回的元组中的两个条目现在被Xcode 7.0.1标记为未解析的标识符错误。

不确定为什么在if代码块中插入实例分配会导致此错误。

是否存在关于在func声明中定义元组然后尝试在if代码块中分配它会导致此错误的事情?

任何人都可以帮助我理解我在这里做错了什么。

以下是代码段:

struct UserInputValidation {
  static var textHasChanged = false
  static var editMode: EditMode?

//  ...

private static func setActions(segueName: String, controller:   UITableViewController) -> (cancelAction: UIAlertAction, doNotCancelAction: UIAlertAction)
{

  if (segueName == "exitToEntityTopicsListingTableViewController")
  {
    let cancelAction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.Cancel) { (action) in
    controller.performSegueWithIdentifier(segueName, sender: controller)
    self.textHasChanged = false
    }
    let doNotCancelAction = UIAlertAction(title: "No", style: .Default) { (action) in
    }
}
return (cancelAction, doNotCancelAction)

}     }

2 个答案:

答案 0 :(得分:0)

在return语句中,返回一个可能尚未实例化的值。因此,如果segue名称不是“exitToEntityTopicsListingTableViewController”,则不会返回任何cancelActiondoNotCancelAction

您必须将return语句移动到if块中,或者实例化cancelActiondoNotCancelAction的默认值

答案 1 :(得分:0)

这个错误消息是由于未能实现基本概念而导致的,因为块内创建的任何var或常量都是块的本地,并且在块外部使用时无法解析。

解决方案是将if块之外的两个常量的声明移动到func块中。

另外,不得不从常量变为var,因为我不能预先指定常量,因为它们不再位于if块中。

所以代码现在看起来像:

private static func setActions(segueName: String, controller: EditTopicAndContentTableViewController) -> (cancelAction: UIAlertAction, doNotCancelAction: UIAlertAction)
{

  var cancelAction: UIAlertAction!
  var doNotCancelAction: UIAlertAction!

// User exits topic and content edit page with unsaved changes - yes   continues exit.
  if (segueName == "exitToEntityTopicsListingTableViewController")
  {
    cancelAction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.Cancel) { (action) in
      controller.performSegueWithIdentifier(segueName, sender: controller)
      self.textHasChanged = false
    }
    doNotCancelAction = UIAlertAction(title: "No", style: .Default) { (action) in
    }
  }
// User accesses edit keywords page with unsaved changes which keywords edit needs changes to be saved.
// Yes is save changes and continue to keywords edit page.
  else if (segueName == "editKeywords")
  {
    cancelAction = UIAlertAction(title: "No", style: UIAlertActionStyle.Cancel) { (action) in
    }
    doNotCancelAction = UIAlertAction(title: "Yes", style: .Default) { (action) in
        controller.saveTopicAndContentToCoreData(controller.coreDataStack)
      self.textHasChanged = false
      controller.performSegueWithIdentifier(segueName, sender: controller)
    }
  }

  return (cancelAction, doNotCancelAction)
}
相关问题