Swift结构不能找到成员

时间:2014-09-27 12:50:46

标签: 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)
    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设为varpublic,但我似乎并不理解这一点。

2 个答案:

答案 0 :(得分:3)

似乎您正在尝试使用结构的静态成员,但您只声明了实例成员。将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
}

答案 1 :(得分:2)

如果@ Kirsteins的假设是正确的,并且您需要将结构值用作静态属性,那么可以采用另一种方法来实现相同的结果,但在我看来更好的方式:使用枚举。

但是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}"
}

并在您的代码段中使用:

class AClass {
    var point:CGPoint!

    init() {
        self.point = Direction.None.toRaw()
    }
}