将变量从一个类传输到另一个类以进行表视图

时间:2015-04-27 08:42:54

标签: ios uitableview swift

我正在尝试将变量从一个类转移到表视图类中,如下所示(excellent code for the table view class) 我在class SecondViewController中收到以下错误:
xnyCats = catRet.mainCats()引发错误Expected Declaration

如何让class SecondViewControllerxnyCats继承class XnYCategories

import UIKit
import Foundation

class XnYCategories {

    var catsXny: [String]

    init(catsXny: [String]) {
        self.catsXny = catsXny
    }

    func mainCats() -> [String] {
        var catsXny = ["Sport", "Recreation", "Travel", "Cultural", "Music"]
        return catsXny
    }
}

let catRet = XnYCategories(catsXny: [""])
var xnyCats = [""]
xnyCats = catRet.mainCats()
xnyCats[1]
import UIKit

class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var tableView: UITableView!
    @IBAction func displayTapped(sender : AnyObject) {

    }

    let textCellIdentifier = "TextCell"

    let catRet = XnYCategories(catsXny: [""])
    var xnyCats = [""]
    xnyCats = catRet.mainCats() //throws an error 'Expected Declaration'

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return xnyCats.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! UITableViewCell

        let row = indexPath.row
        cell.textLabel?.text = xnyCats[row]

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        let row = indexPath.row
        println(xnyCats[row] + String(row))
    }
}

1 个答案:

答案 0 :(得分:0)

通过检查您的代码,我发现您无法从其他类调用mainCats()函数,因此有不同的方法来调用函数
1:创建类对象并调用函数,例如

 class Demo {
    func display() {
       println("Hello")
    }
}
 var d = Demo()
 d.display()

2:声明类函数并调用它。例如

 class Demo {
      class func display() {
        println("Hello")
     }
 }

Demo.display()

现在在代码中进行以下修改,然后获得结果

class XnYCategories {

var catsXny: [String]
init (catsXny: [String]){
    self.catsXny = catsXny
}


class func mainCats() -> [String] {
    var catsXny = ["Sport", "Recreation", "Travel", "Cultural", "Music"]
    return catsXny
}


} 
 let catRet = XnYCategories.mainCats()
    println(catRet)