Arbitur
Arbitur

Reputation: 39081

Swift struct not finding members

I have this struct:

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
}

And I try to use it like this:

class AClass {
    var point:CGPoint!

    init() {
        self.point = Direction.None // Direction.Type does not have a member named 'None'
    }
}

I've tried to set .None to a var and public but I don't seem to understand this.

Upvotes: 2

Views: 579

Answers (2)

Antonio
Antonio

Reputation: 72750

If @Kirsteins's supposition is correct, and you need to use the struct values as static properties, then there's an alternative way of achieving the same result, but in my opinion in a better way: using an enum.

But swift enums accept characters, strings and numbers as raw values only, whereas a CGPoint is made up of a pair of floats. Fortunately swift gives us the capability of using a string literal to specify the pair, which is then converted into a CGFloat:

extension CGPoint : StringLiteralConvertible {
    public static func convertFromStringLiteral(value: StringLiteralType) -> CGPoint {
        return CGPointFromString(value)
    }

    public static func convertFromExtendedGraphemeClusterLiteral(value: StringLiteralType) -> CGPoint {
        return convertFromStringLiteral(value)
    }
}

This extension allows us to initialize a CGFloat as follows:

let point: CGPoint = "{1, -3}"

With that in our hands, we can define an enum as follows:

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

and use in your code snippet as:

class AClass {
    var point:CGPoint!

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

Upvotes: 2

Kirsteins
Kirsteins

Reputation: 27335

Seems that you are trying to use static members of the struct, but you have only declared instance members. Add static to all properties.

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
}

Upvotes: 3

Related Questions