Struct Swift结构找不到成员
我有这个结构:Struct Swift结构找不到成员,struct,swift,Struct,Swift,我有这个结构: struct Direction { let Left = CGPoint(x: -1, y: 0) let Top = CGPoint(x: 0, y: -1) let Right = CGPoint(x: 1, y: 0) let Down = CGPoint(x: 0, y: 1) let TopLeft = CGPoint(x: -1, y: -1) let TopRight = CGPoint(x: 1, y: -1)
struct Direction {
let Left = CGPoint(x: -1, y: 0)
let Top = CGPoint(x: 0, y: -1)
let Right = CGPoint(x: 1, y: 0)
let Down = CGPoint(x: 0, y: 1)
let TopLeft = CGPoint(x: -1, y: -1)
let TopRight = CGPoint(x: 1, y: -1)
let DownLeft = CGPoint(x: -1, y: 1)
let DownRight = CGPoint(x: 1, y: 1)
let None = CGPointZero
}
我试着这样使用它:
class AClass {
var point:CGPoint!
init() {
self.point = Direction.None // Direction.Type does not have a member named 'None'
}
}
我试图将
.None
设置为var
和public
,但我似乎不明白这一点。似乎您试图使用结构的静态成员,但您只声明了实例成员。将static
添加到所有属性
struct Direction {
static let Left = CGPoint(x: -1, y: 0)
static let Top = CGPoint(x: 0, y: -1)
static let Right = CGPoint(x: 1, y: 0)
static let Down = CGPoint(x: 0, y: 1)
static let TopLeft = CGPoint(x: -1, y: -1)
static let TopRight = CGPoint(x: 1, y: -1)
static let DownLeft = CGPoint(x: -1, y: 1)
static let DownRight = CGPoint(x: 1, y: 1)
static let None = CGPointZero
}
如果@Kirsteins的假设是正确的,并且您需要使用struct值作为静态属性,那么有另一种方法可以实现相同的结果,但在我看来是更好的方法:使用enum 但是swift枚举只接受字符、字符串和数字作为原始值,而
CGPoint
由一对浮点组成。幸运的是,swift使我们能够使用字符串文字来指定对,然后将其转换为CGFloat
:
extension CGPoint : StringLiteralConvertible {
public static func convertFromStringLiteral(value: StringLiteralType) -> CGPoint {
return CGPointFromString(value)
}
public static func convertFromExtendedGraphemeClusterLiteral(value: StringLiteralType) -> CGPoint {
return convertFromStringLiteral(value)
}
}
此扩展允许我们初始化CGFloat
,如下所示:
let point: CGPoint = "{1, -3}"
enum Direction : CGPoint {
case Left = "{-1, 0}"
case Top = "{0, -1}"
case Right = "{1, 0}"
case Down = "{0, 1}"
case TopLeft = "{-1, -1}"
case TopRight = "{1, -1}"
case DownLeft = "{-1, 1}"
case DownRight = "{1, 1}"
case None = "{0, 0}"
}
有了它,我们可以如下定义枚举:
let point: CGPoint = "{1, -3}"
enum Direction : CGPoint {
case Left = "{-1, 0}"
case Top = "{0, -1}"
case Right = "{1, 0}"
case Down = "{0, 1}"
case TopLeft = "{-1, -1}"
case TopRight = "{1, -1}"
case DownLeft = "{-1, 1}"
case DownRight = "{1, 1}"
case None = "{0, 0}"
}
并在代码段中用作:
class AClass {
var point:CGPoint!
init() {
self.point = Direction.None.toRaw()
}
}
Daeem,这实际上是我一开始想要的,但我甚至不知道这是可能的,所以我问了一个结构!