在 Swift 中没有 Class/Struct 自动完成

No Class/Struct Autocomplete in Swift

目前我的示例代码中有两个结构和一个 class。一种结构用于 Tiger,一种用于 Balloon,另一种用于 Lion。每个如下:

struct Tiger {
    var name = ""
    var age = 0
    var breed = ""
    var image = UIImage(named: "")
    func chuff() {
        println("\(name): Chuff Chuff")
    }
    func chuffNumberOfTimes(numberOfTimes:Int) {
        for (var i = 0; i < numberOfTimes; i++) {
            self.chuff()
        }
    }
    func ageInTigerYearsFromAge(regularAge:Int) -> Int {
        return regularAge * 3
    }
    func randomFact() -> String {
        let randomFactNumber = Int(arc4random_uniform(UInt32(3)))
        var randomFact:String
        switch randomFactNumber {
        case 0:
            randomFact = "Tigers are 10 feet tall."
        case 1:
            randomFact = "Tigers are amazing."
        case 2:
            randomFact = "Tigers have 10 feet."
        default:
            randomFact = ""
        }
        return randomFact
    }
}
struct Balloon {
    var number = 0
    var image = UIImage(named: "")
}
class Lion {
    var name = ""
    var age = 0
    var isAlphaMale = false
    var image = UIImage(named: "")
    var subSpecies = ""
}

每个文件都在自己的文件中,文件名与 struct/class 和“.swift”相同。然而,唯一一个在输入 ViewController.swift 时自动完成的是 Tiger 结构。例如,如果我要设置 myTiger = Tiger( 它会建议 name: String, age: Int 等。我怎样才能让其他两个也这样做?我真的很喜欢内联定义变量,而不是用 5 行代码来定义所有变量。

有人知道它是如何工作的吗?或者为什么 Tiger 结构会这样做而 Balloon 和 Lion 结构却不会?

类 不要像 Struct 那样免费获得初始化器,如果你想为 class 提供初始化器,你必须创建它:

class Lion {
    var name = ""
    var age = 0
    var isAlphaMale = false
    var image = UIImage(named: "")
    var subSpecies = ""

    init(name: String, age:Int, isAlphaMale: Boolean, image: UIImage, subSpecies: String){
        self.name = name 
        self.age = age 
        self.isAlphaMale = isAlphaMale 
        self.image = image 
        self.subSpecies = subSpecies 
    }
} 

Balloon 应该会自动工作,可能会在您的代码中进行清理和构建,因此 xcode 可以更新将解决问题。

来自Apple Documentation

结构类型的成员初始化器

All structures have an automatically-generated memberwise initializer, which you can use to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name:


copied from a previus part of the document to add context

struct Resolution { var width = 0 var height = 0 }


let vga = Resolution(width: 640, height: 480)

Unlike structures, class instances do not receive a default memberwise initializer.

使用上面的 class,您将拥有如下屏幕截图所示的初始化程序:

正如您在屏幕截图中看到的那样,气球也可以正常工作

无需输入一次即可开始工作,xcode 并不完美,有时它需要一个干净的新构建以使其与您的 classes 和结构同步。