无法在Swift的ViewController类中创建子类的对象

萨维
  1. 我创建了一个名为“ Treasure.swift”的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)
            }
        }
    
  2. 然后创建一个“ ViewController.swift”类并添加以下代码:

    import UIKit
    
    class ViewController: UIViewController
    {
        var treasures : [Treasure] = []
    
        override func viewDidLoad()
        {
            super.viewDidLoad()
    
            self.treasures = [HistoryTreasure()]
       }
     }
    
  3. 问题是,我创建了ViewController类'treasures'的属性,并将其声明为'Treasure'类型的数组。当我在上面的数组中插入对象时,像这样:“ self.treasures = [Treasure(what: "hi", longitude: -37, latitude: 78),]”,它运行良好,但是当我尝试插入类型为“ HistoryTreasure”(“ Treasure”的子类)的对象时,它向我们显示了错误:“使用未解析的标识符“历史宝藏””。

  4. 而且,此“ ViewController”类也无法独立识别“ Historytreasure”类,即无法导入。请帮助我理解以上几点。

萨维
  1. 我在@nhgrif的注释的帮助下在上面的代码中发现了错误。第一个问题是错误,我正在创建“宝藏”类的嵌套类“ HistoryTreasure”。但是我想做一个超类“宝藏”的简单子类(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)
         }
    }`
    
  2. 现在,我的代码运行得非常好,并且能够在ViewController类的“ Treasure”类型数组中生成和插入“ HistoryTreasure”子类的对象

self.treasures = [HistoryTreasure(what: "hi", year: 1992, latitude: -37, longitude: 420)]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章