我创建了一个名为' Treasure.swift'的快速课程。并在同一个文件中创建它的子类,如下所示:
import Foundation
class Treasure
{
let what: String
let latitude: Double
let longitude: Double
init ( what: String, latitude: Double, longitude: Double)
{
self.what = what
self.latitude = latitude
self.longitude = longitude
}
class HistoryTreasure: Treasure
{
let year: Int
init(what: String, year: Int, latitude: Double, longitude: Double)
{
self.year = year
super.init(what: what, latitude: latitude, longitude: longitude)
}
}
然后我创建了一个' ViewController.swift'类并添加以下代码:
import UIKit
class ViewController: UIViewController
{
var treasures : [Treasure] = []
override func viewDidLoad()
{
super.viewDidLoad()
self.treasures = [HistoryTreasure()]
}
}
问题是,我创建了ViewController类的一个属性' treasures'并将其声明为“宝藏”的数组。类型。当我在上面的数组中插入对象时:" self.treasures = [Treasure(what: "hi", longitude: -37, latitude: 78),]
",它运行正常,但是当我尝试插入类型为' HistoryTreasure' (' Treasure'的子类),然后它显示我们错误:"使用未解析的标识符' HistoryTreasure'"。
还有这个' ViewController'上课无法确定历史上的好处'独立地上课,即能够导入它。请帮助我理解上述观点。
答案 0 :(得分:1)
我在@ nhgrif评论的帮助下,在上面的代码中发现了错误。第一个问题是错误的,我正在创建'Treasure'类的嵌套类'HistoryTreasure'。但我想创建一个超级'Treasure'的简单子类(HistoryTreasure)。所以我在我的代码中进行了以下更改(在'HistoryTreasure'类开始之前关闭'Treasure'类的花括号):
class Treasure : NSObject
{
let what: String
let latitude: Double
let longitude: Double
init ( what: String, latitude: Double, longitude: Double)
{
self.what = what
self.latitude = latitude
self.longitude = longitude
}
}
class HistoryTreasure: Treasure
{
let year: Int
init(what: String, year: Int, latitude: Double, longitude: Double)
{
self.year = year
super.init(what: what, latitude: latitude, longitude: longitude)
}
}`
现在我的代码运行得非常好,能够在ViewController类的
self.treasures = [HistoryTreasure(what: "hi", year: 1992, latitude: -37, longitude: 420)]