繁体   English   中英

通过结构和数组PopulateTableview

[英]PopulateTableview via Structs & Arrays

    struct Games {
    var GameName        :   String
    var GameCheats      :   [Cheats]
}

struct Cheats {
    var CheatName           :   String
    var CheatCode           :   String
    var CheatDescription    :   String
}

let COD4 = Games(GameName: "Name", GameCheats: [Cheats(CheatName: "Cheat", CheatCode: "Code", CheatDescription: "Description")])

上面的代码是我当前在测试项目中的一个快速文件中的代码。 我现在正尝试从上方获取值以填充表格视图,请参见下文:

class GamesListViewController: UITableViewController {

    var ArrayOfGames = [COD4]

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

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

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
        cell.textLabel?.text = ArrayOfGames[indexPath.row]
        return cell
    }

}

但是我收到一个错误:“无法将类型值'Games'分配给类型'String?'

我是新手,但是确实有php的经验,我正竭尽全力在:(

感谢您的帮助。

亲切的问候罗里

单元格的textLabel?.text类型为String 您正在尝试为其分配Game

cell.textLabel?.text = ArrayOfGames[indexPath.row]

您需要从Game对象创建一个字符串来描述您的游戏。 最简单的解决方案是使用name

cell.textLabel?.text = ArrayOfGames[indexPath.row].GameName

这将编译并运行。 Cell的标签将与您的游戏名称相对应。

可以通过作弊列表来形成更有趣的描述:

let cheatList = ArrayOfGames[indexPath.row]
    .GameCheats
    .map { "\($0.CheatName): \($0.CheatCode) \($0.CheatDescription)" }
    .joinWithSeparator(", ")
cell.textLabel?.text = "\(ArrayOfGames[indexPath.row].GameName) \(cheatList)"

ArrayOfGames[indexPath.row]返回Games结构。 您不能将其分配给标签的text属性(期望使用String? )。 我假设您打算在结构上使用GameName属性。 例如:

cell.textLabel?.text = ArrayOfGames[indexPath.row].GameName

但更重要的是,您应该考虑重新考虑您的命名。 您应遵循的一些约定是:

  • 属性和方法名称应以小写字母开头,并以camelCase命名

  • 类,结构,枚举和协议名称应以大写字母开头,并跟随CamelCase

  • 除非它们实际上代表复数形式,否则类和结构名称应为单数形式(即如果仅代表一个Games则不是游戏)

  • 您应避免在其属性中重复结构的名称(即Game结构中的gameName

  • 如果属性名称已经具有明确的含义,则应避免在其名称中重复属性的类型(即games ,而不是arrayOfGames

因此,用于代码的更常规的命名系统如下所示:

struct Game {
    var name : String
    var cheats : [Cheat]
}

struct Cheat {
    var name : String
    var code : String
    var description : String
}


class GamesListViewController: UITableViewController {

    var games = [game1, game2, game3, ... gameN]

    ...


   cell.textLabel?.text = games[indexPath.row].name

Ray Wenderlich有一个非常不错的Swift样式指南 ,我建议您看看。

暂无
暂无

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

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