swift3中的编译错误:' AnyObject'不是' NSObject'的子类型。

时间:2016-12-23 08:56:27

标签: ios swift3

在基于Swift 3的编译过程中遇到以下错误。

class DetailViewController: UIViewController {

      @IBOutlet weak var detailDescriptionLabel: UILabel!


      var detailItem: AnyObject? {
        didSet {
            // Update the view.
            self.configureView()
        }
      }

      func configureView() {
        // Update the user interface for the detail item.
        if let detail: AnyObject = self.detailItem {
            if let label = self.detailDescriptionLabel {
                label.text = detail.valueForKey("timeStamp")!.description
            }
        }
      }

      override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.configureView()
      }

      override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
      }


    }

错误:

  

/.../ DetailViewController.swift:27:33:' AnyObject'不是的子类型   ' NSObject的'

2 个答案:

答案 0 :(得分:2)

if let detail: [String: AnyObject] = self.detailItem {
        if let label = self.detailDescriptionLabel {
            label.text = detail.valueForKey("timeStamp")!.description
        }
    }

如果detailItem用于存储JSON对象,则最好在开头将其强制转换为字典。好像变量被转换为AnyObject一样,编译将继续提示错误,因为它根本无法处理它(对于你的情况,AnyObject类没有valueForKey函数)。

答案 1 :(得分:1)

我刚把它改成了这个。然后它修复了。

label.text = (detail.value(forKey: "timeStamp") as! NSObject).description