2014-09-27 29 views
2

我有這樣的結構:斯威夫特結構沒有找到成員

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

我試圖設置.Nonevarpublic但我似乎並不瞭解這一點。

回答

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

如果@ Kirsteins的假設是正確的,你需要爲靜態屬性,那麼就實現了同樣的結果的另一種方法,可使用結構值,但在我以更好的方式意見:使用枚舉。

但是,快速枚舉只接受字符,字符串和數字作爲原始值,而CGPoint由一對浮點組成。幸運迅速的給我們使用一個字符串指定一對,然後將其轉化成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() 
    } 
} 
+0

Daeem,這實際上是我一開始想要的,但是甚至沒有知道這是可能的,所以問了一個struct! – Arbitur 2014-09-27 14:23:46