XCode 6 B6
尝试创建一个可以从评估CGVector的逻辑创建的枚举,如下所示:
enum Direction:Int, Printable{
case None = 0
case North, South, East, West, NorthEast, NorthWest, SouthEast, SouthWest
var description: String{
switch (self){
case .None:
return "static"
case .North:
return "north"
case .South:
return "south"
case .East:
return "east"
case .West:
return "west"
case .NorthEast:
return "north-east"
case .NorthWest:
return "north-west"
case .SouthEast:
return "south-east"
case .SouthWest:
return "south-west"
}
}
}
extension Direction {
func fromCGVector(vector:CGVector) -> Direction{
var vectorDir = (dx:vector.dx, dy:vector.dy)
switch(vectorDir){
case (0.0, 0.0):
return Direction.None
case let (0.0,y) where y > 0.0:
return Direction.North
case let (0.0,y) where y < 0.0:
return Direction.South
case let (x, 0.0) where x > 0.0:
return Direction.East
case let (x, 0.0) where x < 0.0:
return Direction.West
case let (x, y) where x > 0.0 && y > 0.0:
return Direction.NorthEast
case let (x, y) where x > 0.0 && y < 0.0:
return Direction.SouthEast
case let (x, y) where x < 0.0 && y > 0.0:
return Direction.NorthWest
case let (x, y) where x < 0.0 && y < 0.0:
return Direction.SouthWest
default:
return Direction.None
}
}
}
var test = Direction.fromCGVector(CGVector(dx:1.0, dy:1.0))
但是收到以下错误:&#39; CGVector无法转换为方向&#39;。
这对我没有意义,因为我没有尝试进行转换,只是调用Direction枚举的静态方法。我认为这可能是一个错误,但我想确保我没有遗漏任何明显的错误。
答案 0 :(得分:1)
我相信您的意思是将该方法声明为static
。看作枚举不能有任何公共构造函数,在类型而不是其中一个案例上调用实例方法是没有意义的。
extension Direction {
static func fromCGVector(vector:CGVector) -> Direction?{
///...
var test = Direction.fromCGVector(CGVector(dx:1.0, dy:1.0))