Swift: unwrapping cause swift compile slowly

前端 未结 2 412
遥遥无期
遥遥无期 2021-01-05 15:00

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

this line of code makes swift compile

相关标签:
2条回答
  • 2021-01-05 15:11

    Yes, I filed a bug report (17585851) on this slow compilation issue, and you should do the same; the more clear use cases Apple is sent, the better. My slow code was several occurrences of this form:

    let title = obj.valueForProperty(MPMediaItemPropertyTitle) as? String
    self.titles += title ? title! : ""
    

    (which, as you can see, is doing nil testing / unwrapping). It was cumbersome but not difficult for me to work around the problem by doing the same thing in a different way, and you should do likewise. But file that bug report first!

    0 讨论(0)
  • 2021-01-05 15:23

    You need to do unwrapping when your types are declared as optionals. In swift an optional type is a type that may or may not have a value. For example i could declare a string as:

    var collegeName : String?

    The "?" at the end of type declaration shows that the collegeName may or may not have a value and in order to get that value you will have to unwrap it in order to get its value by using ! operator.

    As far as i can tell in your case the name field is declared as a string while year , make and model are declared as optional strings that is why you need to unwrap those fields to get the value out of them.

    You can also declared a type using "!" operator like:

    var collegeName : String!

    This means that this is an optional string but it is automatically unwrapped for you so you don't need to use the "!" afterwards to unwrap this optional.

    0 讨论(0)
提交回复
热议问题