有一次,当我在开发一个Swift项目的时候,Xcode陷入了"编译Swift源"状态栏中的消息。无论我等多久,汇编都没有完成。我回滚了我最近的更改,很快意识到编译器的混乱是一个非常简单的枚举构造。下面是一个说明问题的Playground示例。
创建一个新的Playground并粘贴此代码。你看到任何输出吗?
// Playground - noun: a place where people can play
import UIKit
enum FastingType: Int {
case NoFast=0, Vegetarian, FishAllowed, FastFree, Cheesefare
}
class Fasting
{
var allowedFood = [
.NoFast: ["meat", "fish", "milk", "egg", "cupcake"],
.Vegetarian: ["vegetables", "bread", "nuts"],
.FishAllowed: ["fish", "vegetables", "bread", "nuts"],
.FastFree: ["cupcake", "meat", "fish", "cheese"],
.Cheesefare: ["cheese", "cupcake", "milk", "egg"]
]
func getAllowedFood(type: FastingType) -> [String] {
return allowedFood[type]
}
}
var fasting = Fasting()
println(fasting.getAllowedFood(.Vegetarian))
println("Hello world")
在我的机器上,忙指示器一直在旋转,没有消息。我在Xcode 6.1(6A1052c)和Xcode 6.2-beta(6C86e)上都试过这个。
这看起来像是Swift编译器中的错误吗?或者我的代码中存在一些问题?
更新
有些人注意到我忘记了getAllowedFood
函数中的返回类型。然而,仅此修复并不能解决问题。编译器仍然挂起。
评论中提出了一种解决方法:
斯威夫特似乎在解释你的词典时遇到了麻烦。通常一个好主意是给词典一个明确的类型来帮助"帮助"编译器。
以下添加" un-freezes"编译器:
var allowedFood: [FastingType: [String]]
答案 0 :(得分:4)
是的,这可以被视为编译器错误。编译器在查找字典中键的类型时遇到问题。通过为字典提供显式类型或确保使用FastingType.NoFast
完全指定第一个值,可以消除无限循环行为。
试试这个:
enum FastingType: Int {
case NoFast=0, Vegetarian, FishAllowed, FastFree, Cheesefare
}
class Fasting
{
var allowedFood:[FastingType: [String]] = [
.NoFast: ["meat", "fish", "milk", "egg", "cupcake"],
.Vegetarian: ["vegetables", "bread", "nuts"],
.FishAllowed: ["fish", "vegetables", "bread", "nuts"],
.FastFree: ["cupcake", "meat", "fish", "cheese"],
.Cheesefare: ["cheese", "cupcake", "milk", "egg"]
]
func getAllowedFood(type: FastingType) -> [String] {
return allowedFood[type]!
}
}
的变化:
allowedFood
类型[FastingType: [String]]
以便它可以解释您的枚举值。getAllowedFood()
一个返回类型。或者,您可以getAllowedFood()
到return allowedFood[type] ?? []
,如果您的字典不详尽,那么会更安全。