10

新しいクラスに取り組んでいる Swift プレイグラウンドで遊んでいます。何らかの理由で、3行前に定義された定数の名前を持つクラスに「メンバー型がありません」というエラーが表示され続けます。コードは次のとおりです。

import Foundation
class DataModel {
    let myCalendar = NSCalendar.autoupdatingCurrentCalendar()

    var myData = [NSDate : Float]()
    let now  = NSDate()
    let components = myCalendar.components(.CalendarUnitYear | .CalendarUnitMonth, fromDate: now)
}

Xcode Beta6 では、最後から 2 行目に「DataModel.Type には 'myCalendar' という名前のメンバーがありません」というエラーが表示され続けます。

違いはないと思いますが、myCalendar を var として定義してみました。

4

2 に答える 2

9

You cannot initialize an instance class property referencing another instance property of the same class, because it's not guaranteed in which order they will be initialized - and swift prohibits that, hence the (misleading) compiler error.

You have to move the initialization in a constructor as follows:

let components: NSDateComponents

init() {
    self.components = myCalendar.components(.CalendarUnitYear | .CalendarUnitMonth, fromDate: now)
}
于 2014-08-30T13:37:23.187 に答える
1

使用したくない場合は@Antonio、別の方法で作成することもできます:structinit

class DataModel {

    struct MyStruct {
        static var myCalendar:NSCalendar = NSCalendar.autoupdatingCurrentCalendar()
        static let now  = NSDate()
    }

    var myData = [NSDate : Float]()

    var components = MyStruct.myCalendar.components(.CalendarUnitYear | .CalendarUnitMonth, fromDate: MyStruct.now)
}

テスト

var model:DataModel = DataModel()
var c = model.components.year  // 2014
于 2014-08-30T13:46:03.633 に答える