UITableView in Swift

前端 未结 17 1382
滥情空心
滥情空心 2020-12-04 08:09

I\'m struggling to figure out what\'s wrong with this code snippet. This is currently working in Objective-C, but in Swift this just crashes on the first line of the method.

17条回答
  •  醉梦人生
    2020-12-04 08:17

    Using "as" keyword would do the following two steps:
    1.creating a optional value which wrap a variable of UITableViewCell;
    2.unwrapping the optional value.

    So,by doing this

    var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Component") as UITableViewCell
    

    you would get a "plain" UITableViewCell type variable: cell.Theoretically speaking, it's ok to do this.But the next line

    if (cell == nil) {}
    

    makes trouble, because in swift, only the optional value can be assigned with nil.

    So, to solve this problem, you have to make cell a variable of Optional type. just like this:

    var cell = tableView.dequeueReusableCellWithIdentifier("Component") as? UITableViewCell
    

    using the keyword "as?" would create a Optional variable, and this, undoubtedly, can be assigned with nil.

提交回复
热议问题