I want to define a function to return a sqrt of a number. but Swift give me an error
func RenderNumber(_ number:Int) -> Int{
for x in 1...number{
if x*x == number{
return x
}
}
}
print(RenderNumber(25))
CodePudding user response:
If a function has a return value you have to return something in any case.
If the square root of number
is not an integer the condition x*x == number
will never be true
.
My suggestion is to return an optional and write the body of the function in a swiftier way
func renderNumber(_ number: Int) -> Int? {
if number <= 0 { return nil }
return (1...number).first{$0 * $0 == number}
}
CodePudding user response:
What you have done is fine, but you are not saying what if condition fails. There is no return if x*x!=number
So update function to below.
func RenderNumber(_ number:Int) -> Int{
var returnValue : Int = 0
for x in 1...number{
if x*x == number{
returnValue = x
break
}
}
return returnValue
}
So here it will return 0 if x*x!=number