扩展:使用未声明类型的错误

时间:2023-01-23 17:48:23

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

我是swift的新手,我想创建Dog类的扩展:

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?

我认为扩展在底部,有人可以帮我这个吗?

2 个解决方案

#1


1  

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

您的Dog类在ViewController类中“隐藏”。在*声明它或将其称为ViewController.Dog。

#2


0  

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.

问题是你已经在另一个类(ViewController)中声明了一个类(Dog) - 这不是第一个 - 因此该类在另一个之外是不可见的。此外,您不必将扩展名放在文件的最后。

Solution

Move the class:

移动课程:

class ViewController: UIViewController { ... }

class Dog {}

extension Dog {}

Solution #2

Change how you refer to the class:

改变你引用课程的方式:

extension ViewController.Dog {}

#1


1  

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

您的Dog类在ViewController类中“隐藏”。在*声明它或将其称为ViewController.Dog。

#2


0  

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.

问题是你已经在另一个类(ViewController)中声明了一个类(Dog) - 这不是第一个 - 因此该类在另一个之外是不可见的。此外,您不必将扩展名放在文件的最后。

Solution

Move the class:

移动课程:

class ViewController: UIViewController { ... }

class Dog {}

extension Dog {}

Solution #2

Change how you refer to the class:

改变你引用课程的方式:

extension ViewController.Dog {}