extension Int {
var isPerfectSquare:Bool {
let sr = sqrt(Double(self))
return ((Int(sr) * Int(sr)) == self)
}
}
The above isPerfectSquare() function extends the Int class. You can call it to check if a number is a perfect square, like this:
print(25.isPerfectSquare) //---true---
print(26.isPerfectSquare) //---false---
print(27.isPerfectSquare) //---false---
print(36.isPerfectSquare) //---true---
No comments:
Post a Comment