gpt4 book ai didi

swift - Swift 中没有类/结构自动完成

转载 作者:搜寻专家 更新时间:2023-11-01 07:34:16 24 4
gpt4 key购买 nike

目前我的示例代码中有两个结构和一个类。一种结构用于 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 = ""
}

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

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

最佳答案

类不会像 Struct 那样免费获得初始化器,如果你想为一个类创建初始化器,你必须创建它:

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.

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

enter image description here

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

enter image description here

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

关于swift - Swift 中没有类/结构自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30972995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com