类型没有成员 [英] Type does not have a member

查看:51
本文介绍了类型没有成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Swift 游乐场玩一个新课程.出于某种原因,我不断收到一个错误,即该类没有成员类型",其中包含三行之前定义的常量名称.代码如下:

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 在倒数第二行一直给我一个错误,说DataModel.Type 没有名为‘myCalendar’的成员

Xcode Beta6 keeps give me an error on the second to last line, saying that "DataModel.Type does not have a member named 'myCalendar'

虽然我不认为它应该有所作为,但我已经尝试将 myCalendar 定义为 var.

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

推荐答案

你不能初始化引用同一个类的另一个实例属性的实例类属性,因为不能保证它们将被初始化的顺序 - swift 禁止这样做,因此(误导)编译器错误.

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

这篇关于类型没有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆