XCode 6 B6
尝试创建一个enum,可以创建一些逻辑评估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))
但是得到以下错误:'CGVector is not convertible to Direction'.
这对我来说没有意义,因为我没有尝试进行转换,只是调用Direction枚举的静态方法。我认为这可能是一个错误,但我想确保我没有错过任何明显的。
我相信你的意思是将该方法声明为static
。由于enum不能有任何公共构造函数,因此在类型上调用实例方法而不是在它的一个case上调用实例方法是没有意义的。
extension Direction {
static func fromCGVector(vector:CGVector) -> Direction?{
///...
var test = Direction.fromCGVector(CGVector(dx:1.0, dy:1.0))