Recap - Safe Unwrapping
Part of the Fundamentals section of Coddy's Swift journey — lesson 15 of 86.
Challenge
EasyWrite 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 letto 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 letto 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
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input