• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Stupid ! and ?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Stupid ! and ?


  • Subject: Re: Stupid ! and ?
  • From: Jonathan Hull <email@hidden>
  • Date: Sat, 25 Apr 2015 08:57:09 -0700

> On Apr 25, 2015, at 7:59 AM, William Squires <email@hidden> wrote:
>
> Where I'm running into problems is this line of code:
>
> func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
> {
> var cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as? UITableViewCell
> if (cell == nil)
>  {
>  cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: simpleTableIdentifier)
>  }
> cell!.textlabel.text = dwarves[indexPath.row] // Problem here
> return cell
> }
>
> Xcode is complaining that a "?" or "!" is needed after "textLabel", and before the ".text", but I don't really understand which one to use.

Using ‘?' here will give you the objC behavior of doing nothing if textLabel is nil.  Using ‘!’ would crash if it ended up as nil for some reason.  When in doubt use ‘?'

> Another line of code that confuses me is the first line:
>
> var cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as? UITableViewCell
>
> yet they use an "!" and not a "?" in the cell!.textLabel.text... line. Shouldn't that be:
>
> cell?.textLabel.text to match up with the ? in the var cell... line?

The ‘!’ basically means: Hey compiler, I know you think this could be nil, but trust me... I promise it won’t be.  In this case, the line above it checks to see if cell is nil and gives it a value, so we know it isn’t nil.  I still prefer to use ‘?’ or ‘if let’ in these cases though.

Thanks,
Jon
_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden


References: 
 >Stupid ! and ? (From: William Squires <email@hidden>)

  • Prev by Date: Stupid ! and ?
  • Next by Date: Re: Stupid ! and ?
  • Previous by thread: Stupid ! and ?
  • Next by thread: Re: Stupid ! and ?
  • Index(es):
    • Date
    • Thread