GabrielxKuek

Swift Functions Exercise

Jan 2nd, 2025 (edited)
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. Swift Function Exercise
  2.  
  3. Sample Example:
  4. Here's how to write a basic function in Swift that adds two numbers:
  5.  
  6. ```
  7. func add(_ x: Int, _ y: Int) -> Int {
  8. return x + y
  9. }
  10. // Using the function:
  11. let result = add(5, 3)
  12. print(result) // Prints: 8
  13. ```
  14.  
  15. Your Task:
  16. Write a function called processOrder that:
  17.  
  18. Takes a string in the format "itemName:quantity@price"
  19. Returns a tuple of (itemName: String, total: Double, isValid: Bool)
  20.  
  21. Requirements:
  22. Extract the item name, quantity, and price from the string
  23. Quantity must be converted from string to Int
  24. Price must be converted from string to Double
  25. Return ("", 0.0, false) if the string format is invalid
  26. Total should be quantity * price
  27.  
  28. Test Cases:
  29. processOrder("iPhone:[email protected]") // Returns ("iPhone", 1999.98, true)
  30. processOrder("Coffee:[email protected]") // Returns ("Coffee", 13.50, true)
  31. processOrder("Laptop:[email protected]") // Returns ("", 0.0, false)
  32. processOrder("Invalid String") // Returns ("", 0.0, false)
  33.  
Advertisement
Add Comment
Please, Sign In to add comment