简体   繁体   English

如何在swift文件中获取类的引用,并在另一个swift文件中进行编码? -xcode /迅速

[英]How do i get a reference of a class in a swift file and code that in another swift file? - xcode / swift

Im new to swift / Xcode and would like to know how to answer this specific question. 我是swift / Xcode的新手,并且想知道如何回答这个特定问题。

The instruction states that i have to " Get a reference to your model in your TableViewController" 该说明指出,我必须“在TableViewController中获取对模型的引用”

So my question is: How do i get a reference to my Model (Model.swift) in my other swift file (TableViewController.swift) ? 所以我的问题是:如何在另一个swift文件(TableViewController.swift)中获得对模型(Model.swift)的引用? What do i have to code in my TableViewController to get a reference? 我必须在TableViewController中进行编码才能获得参考?

My Model.swift file contains the following code: 我的Model.swift文件包含以下代码:

import UIKit

class Restaurant
{
  var name: String
  var phone: String

  init(name:String, phone:String)
  {
    self.name = name
    self.phone = phone
  }
}

Thanks. 谢谢。

You can create an instance of Restaurant, possibly in your TableViewController. 您可以在TableViewController中创建Restaurant的实例。 Let us assume, you are displaying an array of restaurants in your table view. 让我们假设,您正在表视图中显示一系列餐厅。

Do this- 做这个-

  1. Define an array inside your table view controller 在表视图控制器中定义一个数组

     var restaurants = [Restaurant]() 
  2. Somewhere in your controller, say in viewDidLoad, create a few restaurant objects and add it the above array 在控制器的某个位置,例如在viewDidLoad中,创建一些餐厅对象并将其添加到上面的数组中

     //Create few restaurant objects restaurants.append(Restaurant(name:"Rest1", phone:"123")) restaurants.append(Restaurant(name:"Rest2", phone:"1234")) restaurants.append(Restaurant(name:"Rest3", phone:"12345")) 
  3. Load the table view with the above objects via the data source delegates. 通过数据源委托使用上述对象加载表视图。

In swift you don't need to import Model.swift, etc, once defined in a file, it is automatically available to the rest of the app unless you restrict its access using access specifiers. 在swift中,您无需导入在文件中定义的Model.swift等,即可自动提供给应用程序的其余部分,除非您使用访问说明符限制对它的访问。

HTH. HTH。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM