-5

I am trying to add code in cellForRowAt indexPath method like below

cell.itemNameLabel.text = nameArray[indexPath.row]

but it is showing error as Cannot assign value of type 'Any' to type 'String?'

so it can be solved by below 2 ways,

cell.fruitName.text = fruitArray[indexPath.row] as? String

or

cell.fruitName.text = (fruitArray[indexPath.row] as! String)

so, my question is what is the difference between 2 answers?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Nikita Patil
  • 674
  • 1
  • 7
  • 17
  • you can unwrap the optional value like: if let name = fruitArray[indexPath.row] as? String { cell.fruitName.text = name } – Saurabh Jain May 08 '18 at 13:19

2 Answers2

1
cell.fruitName.text = fruitArray[indexPath.row] as? String

Above return type is optional value. means it will be nil value return if array is not consist string value.

cell.fruitName.text = (fruitArray[indexPath.row] as! String)

Above return type is non-optional value. means it will be fire fatal error if array is not consist string value.

Rakesh Patel
  • 1,673
  • 10
  • 27
0

Below is the generic information for all optionals. Please find it.

When you are using ! and the fruitArray[indexPath.row] is nil it will trigger run time error but if use ? it will fail gracefully.

You can find more detail information in Apple document

PPL
  • 6,357
  • 1
  • 11
  • 30
  • so cell.fruitName.text = (fruitArray[indexPath.row] as! String) is better way to use it? – Nikita Patil May 08 '18 at 11:48
  • 2
    @NikitaPatil No, force wrapping means it will crash if it is `nil`. It's always better to check for value before unwrapping. – saurabh May 08 '18 at 11:50
  • I told already that if it is non nil, better solution check with if let before using it – PPL May 08 '18 at 11:52
  • 1
    The OP is not using `!`, they're using `as!`. That's a force cast, which is a little different than a force unwrap. `let x = "x" as! Int` will crash because "x" can't be cast to an Int. – Duncan C May 08 '18 at 12:34