上QQ阅读APP看书,第一时间看更新
How to do it...
- Create a new playground file in Xcode called Extensions.
- Create extension for double value by adding computing properties, as follows:
extension Double{ var absoluteValue: Double{ return abs(self) } var intValue: Int{ return Int(self) } } extension String{ var length: Int{ return self.characters.count } } let doubleValue: Double = -19.5 doubleValue.absoluteValue // 19.5 doubleValue.intValue // 19 extension Int{ func isEven() ->Bool{ return self % 2 == 0 } func isOdd() ->Bool{ return !isEven() } func digits() -> [Int]{ var digits = [Int]() var num = self repeat { let digit = num % 10 digits.append(digit) num /= 10 } while num != 0 return digits } } let num = 12345 num.digits() // [5, 4, 3, 2, 1]