monekypox121
monekypox121

Reputation: 93

Extension: error use of undeclared type

I am new to swift, and I would like to create an extension of the Dog class:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    public class Dog {
        var name = "Timmy"
    }
}

extension Dog {
    func description() -> String {
        return "A dog named \(self.name)"
    }
}

I thought extensions go at the way bottom, can someone help me with this?

Upvotes: 0

Views: 2666

Answers (2)

LinusG.
LinusG.

Reputation: 28912

The problem is that you have declared a class (Dog) inside another class (ViewController) - which is a don't in the first place - and so the class is not visible outside the other. Also, you don't have to put an extension at the very end of a file.

Solution

Move the class:

class ViewController: UIViewController { ... }

class Dog {}

extension Dog {}

Solution #2

Change how you refer to the class:

extension ViewController.Dog {}

Upvotes: 0

matt
matt

Reputation: 535232

Your Dog class is "hidden" inside your ViewController class. Declare it at top level or refer to it as ViewController.Dog.

Upvotes: 1

Related Questions