【问题标题】:Swift calling public class in another fileSwift 在另一个文件中调用公共类
【发布时间】:2023-04-05 08:22:01
【问题描述】:

在 Swift 编程中。我创建了一个名为 Array3d 的公共类,位于 Array3d.swift 文件中。我的 ViewController2.swift 使用 Array3d 类和我的 println(dog) 创建了一个名为 dog 的变量。但是,我的控制台没有显示 dog 数组的值,而是显示 FYP_Table.Array3D 。

我创建了一个名为 dog 的 3D 数组,并在其中插入了一些值。现在我想将它打印到我的调试器输出。但不起作用。

// Array3d.swift 
    public class Array3D {
        var zs:Int, ys:Int, xs:Int
        var matrix: [Float]

        init(zs: Int, ys:Int, xs:Int) {
            self.zs = zs
            self.ys = ys
            self.xs = xs
            matrix = Array(count:zs*ys*xs, repeatedValue:0)
        }

        subscript(z:Int, y:Int, x:Int) -> Float {
            get {
                return matrix[ z * ys * xs + y * xs + x ]
            }
            set {
                matrix[ z * ys * xs + y * xs + x ] = newValue
            }
        }

//ViewController2.swift

    class ViewController2: UITableViewController {

    var dog = Array3D(zs: 3, ys: 3, xs: 3)


    override func viewDidLoad() {

    dog[1,0,0] = 1
    dog[0,4,0] = 2
    dog[0,0,4] = 3
    dog[0,4,4] = 4

      for z in 0..<3 {
       for y in 0..<3 {
        for x in 0..<3 {
         println(self.dog)
               }
             }
           }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }

    }

【问题讨论】:

    标签: ios class swift public


    【解决方案1】:

    你的类没有description,所以它只是打印出默认表示。

    func description() -> String {
      return String(format: "Array3D zs:%d ys:%d xs:%d", self.zs, self.ys, self.zs)
    }
    

    【讨论】:

    • 只是一个补充:如果你使用它会更“迅速”:return "Array3D zs: \(zs) ys: \(ys) xs: \(xs)"
    • 可能;我从来没有真正快速地编写过任何东西。 ;)
    • 从技术上讲,您必须让您的类实现 Printable 类别,这意味着实现描述(作为属性)以及添加类的声明,如 @fred 的链接所示。跨度>
    • 嗨.. 但我想返回包含其中值的数组,例如 dog[z,y,x]。然后在 ViewController2 中,我将要打印出我的 3D 数组,并且我将使用 for 循环。如何返回包含值的数组?对不起,如果我问一个简单的问题,这里是编程初学者..
    • 上面提供的代码是否存在您可以描述的特定问题?我不确定你在这里问什么。
    【解决方案2】:

    执行此操作的正确方法是实现Printable 协议(请参阅here),它只是一个名为description 的只读属性。

    var description : String {
        return String(format: "Array3D zs:%d ys:%d xs:%d", zs, ys, zs)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多