Menu
Coddy logo textTech

Recap - Safe Unwrapping

Part of the Fundamentals section of Coddy's Swift journey — lesson 15 of 86.

challenge icon

Challenge

Easy
Write a function formatPlayerInfo that takes a player's name, score, and level as strings and returns a formatted player summary.

Use all three unwrapping techniques you've learned to handle potentially missing values:

  • Use guard let to check if the name is valid (non-empty). If the name is empty, return "Unknown player" immediately.
  • Use ?? (nil coalescing) to provide a default score of "0" if the score is empty.
  • Use if let to check if the level is valid (non-empty). If it has a value, include it in the output; otherwise, omit the level part.

Output Format:

  • If level is provided: "[name] - Score: [score], Level: [level]"
  • If level is empty: "[name] - Score: [score]"

Parameters:

  • name (String): Player's name (empty string represents nil)
  • score (String): Player's score (empty string represents nil)
  • level (String): Player's level (empty string represents nil)

Returns: A formatted string with the player's information, or "Unknown player" if the name is empty.

Hint: Convert empty strings to optionals inside your function by checking if they're empty and assigning nil if so.

Try it yourself

func formatPlayerInfo(name: String, score: String, level: String) -> String {
    // Write code here
}

All lessons in Fundamentals