【问题标题】:Variable courseTitle was never mutated变量 courseTitle 从未发生过变异
【发布时间】:2016-02-19 11:16:40
【问题描述】:

伙计们,我收到了这个错误

变量 courseTitle 从未改变

在尝试使用“dequeueReusableCellWithIdentifier”时。

这是我的代码:

import UIKit

class ViewController: UIViewController, UITableViewDataSource {

    let devCourses = [("iOS App Dev with Swift Essential Training","Simon Allardice"),
        ("iOS 8 SDK New Features","Lee Brimelow"),
        ("Data Visualization with D3.js","Ray Villalobos"),
        ("Swift Essential Training","Simon Allardice"),
        ("Up and Running with AngularJS","Ray Villalobos"),
        ("MySQL Essential Training","Bill Weinman"),
        ("Building Adaptive Android Apps with Fragments","David Gassner"),
        ("Advanced Unity 3D Game Programming","Michael House"),
        ("Up and Running with Ubuntu Desktop Linux","Scott Simpson"),
        ("Up and Running with C","Dan Gookin")]


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

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
        {

            let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell

            var (courseTitle, courseAuthor) = devCourses[indexPath.row]

            cell.textLabel?.text = courseTitle
            return cell

        }

有什么想法吗?

【问题讨论】:

  • 另请阅读警告的第二部分,这就是 idea
  • 它说:从未使用过变量“courseAuthor”;考虑用“_”替换或删除它
  • 这是一个新警告,我的意思是您问题中提到的原始警告。无论如何,编译器总是试图给出合理的建议。

标签: ios xcode swift


【解决方案1】:

您允许更改课程标题。将 var 更改为 let:

let (courseTitle, courseAuthor) = devCourses[indexPath.row]

在 Swift 开发中,始终默认使用 let 是一个好主意,然后仅在需要进行更改时才更改为 var。

【讨论】:

  • 编译后出现 SIGABRT 错误。
  • let (courseTitle, _) = devCourses[indexPath.row] 更好
  • 将其更改为“_”时也会出现 SIGABRT 错误。
  • 如果注释掉设置单元格文本的行,是否还会出现这个 SIGABRT 错误?
  • 是的,我愿意。如果这是您的意思:“ //cell.textLabel?.text = courseTitle”
【解决方案2】:

将 var 更改为 let,因为您没有改变 courseTitle 或 courseAuthor 的值。

let courseInfo = devCourses[indexPath.row]
cell.textLabel?.text = courseInfo.0

【讨论】:

  • 但我正在尝试传递 2 个参数(courseAuthor 和 courseTitles)。你的包含一个论点。还是我错过了什么?
  • 啊!我看到你在那里做了什么;有意义,因为它会传递两个常量。但是就没有办法通过这两个吗?
  • 通过这两个是什么意思?您的意思是连接元组中的两个字符串吗?
  • 是的。传递两个字符串而不是一个。
  • 你可以用 courseInfo.0 + courseInfo.1 连接两个字符串
猜你喜欢
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 2016-08-21
  • 2018-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多