我在类初始值设定项(名为 Building 的类)中使用名为 BuildingType 的枚举变量。
这个枚举是在类外部定义的,因为我想在其他地方也使用它。
初始化变量 typeOfBuilding 时,此枚举的自动完成功能无法正常工作。
示例代码:
enum BuildingType {
case Flat, House, Villa
}
class Building {
var type : BuildingType = BuildingType.House
var floors : Int = 1
init(typeOfBuilding : BuildingType, numFloors : Int) {
self.type = typeOfBuilding
self.floors = numFloors
}
}
var myBuilding : Building = Building(typeOfBuilding: BuildingType.Flat , numFloors: 3)
因此,如果我输入“... typeOfBuilding: BuildingType。” (初始化 myBuilding 时)显示“楼层”和“类型”,而不是枚举值。
我一定是做错了什么,但是什么?
最佳答案
这是一个非常奇怪的错误
当您尝试将枚举传递到初始化程序的参数中时,自动完成将失败,并且不会在输入 Enum.
后建议枚举案例,而是列出该类的实例成员你正在调用初始化程序。如果您尝试使用单点语法 (.Case
),自动完成也会失败,但它不会显示实例成员列表,而是不会显示任何内容。
我最初认为这可能与枚举和类的命名(BuildingType
& Building
)有关,但事实并非如此。
此错误似乎仅存在于具有多个参数(其中一个是枚举)的初始化程序中。我无法使用单参数初始化程序重现此问题。
再现性似乎取决于初始化程序是否“完整”。如果初始化程序定义了所有参数名称和值(枚举除外),我认为它是“完整的”。例如:
// Incomplete (foo is one argument of many)
let baz = Baz(foo: Foo.
// Semi-Complete (before you assign the second parameter a value)
let baz = Baz(foo: Foo., string: <String Placeholder>)
// Complete
let baz = Baz(foo: Foo., string: "")
// Complete (note the lack of the last bracket)
let baz = Baz(param: 0, foo: Foo.
这是我的测试设置(Xcode 7.3、Swift 2.2):
enum Foo {
case Bar
}
class Baz {
var iReallyShouldntBeDisplayedHere = 0
init(foo:Foo, string:String) {}
init(foo: Foo) {}
}
以下是我发现错误发生和未发生的案例列表:
// Enum is the only argument
// CORRECT: accepting the initialiser's autocomplete (so it's 'complete'), then typing "Foo." brings up autocomplete options for enum cases
let baz = Baz(foo: Foo.)
// CORRECT: typing the initialiser yourself (so it's 'incomplete'), then typing "Foo." in the first parameter brings up autocomplete options for enum cases
let baz2 = Baz(foo: Foo.
// Enum is one argument of many
// INCORRECT: accepting the initialiser's autocomplete (so it's 'semi-complete'), then typing "Foo." in the first parameter brings up Baz's instance members ("iReallyShouldntBeDisplayedHere")
let baz3 = Baz(foo: Foo., string: <String Placeholder>)
// CORRECT: typing the initialiser yourself (so it's 'incomplete'), and typing "Foo." in the first parameter brings up enum cases
let baz4 = Baz(foo: Foo.
// Single dot syntax (where enum is one argument of many)
// CORRECT: typing the initialiser yourself (so it's 'incomplete'), and typing "." in the first parameter brings up enum cases
let baz5 = Baz(foo:.
// CORRECT: accepting the initialiser's autocomplete (so it's 'semi-complete'), then typing "." in the first parameter brings up enum cases
let baz6 = Baz(foo:., string: <String Placeholder>)
// INCORRECT: modifying the foo: argument once the initialiser is 'complete' by typing "." in the first parameter doesn't generate the autocomplete list
let baz7 = Baz(foo:., string: "")
我也尝试过这个,其中 foo:
是最后一个参数,但在这种情况下初始化程序总是必须完整,所以它总是失败。我确实尝试过使用带有 3 个参数的初始化程序,但它似乎与带有 2 个参数的初始化程序具有相同的行为。
如果有人知道更多可以重现此错误的情况,我很想知道!
关于swift - 枚举在自定义初始值设定项中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38141127/