Type does not have a member

给你一囗甜甜゛ 提交于 2019-12-27 15:56:45

问题


I'm playing around with a Swift playground working on a new class. For some reason I keep getting an error that the class "does not have a member type" with the name of a constant defined three lines earlier. Here is the code:

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 keeps give me an error on the second to last line, saying that "DataModel.Type does not have a member named 'myCalendar'

Though I don't think it should make a difference, I have tried defining myCalendar as a var.


回答1:


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



回答2:


I agree with @Antonio The other way might be to create struct if you don't want to use init:

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

Test

var model:DataModel = DataModel()
var c = model.components.year  // 2014


来源:https://stackoverflow.com/questions/25582853/type-does-not-have-a-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!