【问题标题】:Why am I getting the error [NSObject : AnyObject]?' does not have a member named 'subscript'为什么我收到错误 [NSObject : AnyObject]?没有名为“下标”的成员
【发布时间】:2014-12-29 21:21:06
【问题描述】:

在下面的removeTextFieldObserver 函数中,我收到错误“[NSObject : AnyObject]?”没有一个名为‘下标’的成员”。如果是字典,它肯定应该有一个下标吗?

func showSimpleAlert() 
{
    let title = NSLocalizedString("A Short Title is Best", comment: "")
    let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "")
    let cancelButtonTitle = NSLocalizedString("OK", comment: "")

    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)

    // Create the action.
    let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
        NSLog("The simple alert's cancel action occured.")
    }

    // Add the action.
    alertController.addAction(cancelAction)

    presentViewController(alertController, animated: true, completion: nil)
}

func removeTextFieldObserver()
{
   NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: alertController.textFields[0])
}

【问题讨论】:

  • textFields 是什么?你是怎么申报的?
  • textFields[0],它是 alertController 在索引 0 处的默认属性
  • 试试。 var arr = alertController.Textfield?作为 NSArray 然后 arr[0]

标签: ios swift subscript


【解决方案1】:

那是因为[NSObject:AnyObject]? 是可选的。它可能包含[NSObject: AnyObject],也可能不包含nil

要使用该值,您需要先“解包”它:

if let object = alertController.textFields?[0] {
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: object)
}

alertController.textFields?[0] 表示“如果alertController.textFields 不是nil,则返回[0]th 元素,否则返回nil。然后if let object = 说“如果右边的值不是nil,打开它并将该值分配给object

【讨论】:

    【解决方案2】:

    textFields 是一个可选属性,要访问下标,您必须将其解包。

    textFields?[0]
    

    应该可以。如果警报控制器没有 textFields,这将发送 nil。

    【讨论】:

      猜你喜欢
      • 2014-12-17
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多