1

I have been following a tutorial on youtube and been coding a twitter like app in xcode and keep returning this error, the tutorial was using an earlier version of swift. How do i move past this?

class HandleViewController: UIViewController {
    @IBOutlet weak var fullName: UITextField!
    @IBOutlet weak var handle: UITextField!
    @IBOutlet weak var startTweeting: UIBarButtonItem!
    @IBOutlet weak var errorMessage: UILabel!

    var user = AnyObject()
    var rootRef = FIRDatabase.database().reference()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.user = FIRAuth.auth()?.currentUser
    }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
jon
  • 19
  • 1
  • Probably a dupe of [What happened to the UIView?() constructor in Swift 3.0?](http://stackoverflow.com/q/39549717/2976878) – Hamish May 03 '17 at 22:09

1 Answers1

1

You're getting that error because AnyObject in Swift is a Protocol, not a class, structure, or enum. A protocol is sort of a blueprint for a class, and you create classes that conform to it, but the protocol itself can never be instantiated.

As for how to fix it: It looks like the tutorial you're following uses the same code as the tutorial here. It assigns a value to user in viewDidLoad, and treats it as an optional after that. So the initial value is just a placeholder that's never getting used.

You can change the declaration to an optional instead, giving it a type but no value:

var user: AnyObject?

AnyObject has always been a Protocol in Swift, so there could never be an instance of it. So why did it work in the previous version of Swift used in the tutorial? Well for one, it looks like there's a typo in your version. In the tutorial it looks like this:

var user = AnyObject?()

The question mark after AnyObject? makes it an Optional of type AnyObject. In Swift prior to 3.0, Optional had an init() method that would create an empty instance. So AnyObject?() was shorthand for a new Optional of type AnyObject, value set to nil. In Swift 3 the superfluous initializer was dropped, so that shorthand no longer works. But just declaring the variable as an optional has the same effect.

Robert
  • 6,660
  • 5
  • 39
  • 62