0

Can You explain to me what this warning message means?

let x = cell.backgroundView!.layer.sublayers as! [CALayer]

Forced cast from '[CALayer]?' to '[CALayer]' only unwraps optionals; did you mean to use '!'?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
David Kramf
  • 207
  • 2
  • 9

1 Answers1

2

Using a forced cast makes no sense. sublayers returns an optional array. You should safely unwrap the optional array.

if let sublayers = cell.backgroundView?.layer.sublayers {
    // do something with sublayers (which is a non-optional [CALayer])
}

Also notice the use of ? after backgroundView instead of !.

Please spend time learning how to properly use optionals by reading the relevant sections in the Swift book. Otherwise your app is going to crash. See What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean? for lot of details about that outcome.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thank You for your answer. When I adopt your suggestion I get a (strange ?) error in the second command - let x = cell.backgroundView!.layer.sublayers let _ = x.map({$0.removeFromSuperlayer()}) which is flagged as error Value of type '[CALayer]' has no member 'removeFromSuperlayer' – David Kramf Dec 20 '17 at 18:41
  • 2
    Now you are asking about an entirely different question. If this answer solved your original question about the cast, then indicate this by accepting this answer. Then post a new question about your new issue with all relevant code and error messages – rmaddy Dec 20 '17 at 19:09
  • I accepted the answer ( by clicking the up arrow?) . The second issue was my original issue which I solved by the cast (as!) but still encountered the warning. Thank you for the effort in solving my issues. David – David Kramf Dec 21 '17 at 10:53
  • You accept an answer by clicking on the checkmark to the left of the answer (just below the votes). – rmaddy Dec 21 '17 at 15:07