'Function with multiple parameters in swift
I need to define and call a function called areaOfRectangle that takes two Int parameters, length, and width, and prints the result of length * width. I actually got result with length * width but it is telling me to make sure I’m defining a function with the correct name and parameters. The answer below will print length * width which is right but the steps are not what it should be.
func areaOfRectangle(length: Int, width: Int) {
print(“length * width”)
}
areaOfRectangle(length: 0, width: 0)
Solution 1:[1]
Here is the way you can return string result from Int parameters:
//define a return type as String here
func areaOfRectangle(length: Int, width: Int) -> String {
print("\(length * width)") //same thing you can print here
return "\(length * width)" //return it as String
}
let result = areaOfRectangle(length: 5, width: 5)
print(result) //"25"
Solution 2:[2]
print(“length * width”)
in this statement length and width are being treated as string literals. Any thing that comes between "" is a string literal at least in swift, also in some other languages.
Swift provide a very good syntactic sugar to use variables and constants within the string by putting the vars and lets within \(). Hence when you correct the above statement to print(“\(length * width)”). It will print correct result of length*width.
Updated code:
func areaOfRectangle(length: Int, width: Int) {
print(“\(length * width)”) //42
}
areaOfRectangle(length: 6, width: 7)
Solution 3:[3]
Explaination: function with multiple parameters., in which the function greet have parameter of alreadyGreeted also a condition it will check when we give argument label of person and bool is true, we call it, and function will start its execution... condition is checked,. then greetAgain function is called with its argument label... and print "hello Again" with person name that is in greet-main function calling parameter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Nadia Tariq |
