swift编程向 Int 类型添加了 4 个计算型属性,分别为: self + 100 self - 10 self * 10 self / 5 以及四种结果的加减乘除混合计算
时间: 2024-01-01 14:03:57 浏览: 31
您可以通过扩展(Int)来为Int类型添加这些计算型属性。下面是一个实现的例子:
```swift
extension Int {
var plus100: Int {
return self + 100
}
var minus10: Int {
return self - 10
}
var times10: Int {
return self * 10
}
var divide5: Int {
return self / 5
}
func calculate(_ operation: (Int, Int) -> Int, with value: Int) -> Int {
return operation(self, value)
}
func add(_ value: Int) -> Int {
return self + value
}
func subtract(_ value: Int) -> Int {
return self - value
}
func multiply(_ value: Int) -> Int {
return self * value
}
func divide(_ value: Int) -> Int {
return self / value
}
}
```
然后,您就可以像这样使用这些计算型属性和方法:
```swift
let number = 42
print(number.plus100) // 输出:142
print(number.minus10) // 输出:32
print(number.times10) // 输出:420
print(number.divide5) // 输出:8
print(number.calculate(+, with: 10)) // 输出:52
print(number.calculate(-, with: 10)) // 输出:32
print(number.calculate(*, with: 10)) // 输出:420
print(number.calculate(/, with: 5)) // 输出:8
print(number.add(10)) // 输出:52
print(number.subtract(10)) // 输出:32
print(number.multiply(10)) // 输出:420
print(number.divide(5)) // 输出:8
```
在上面的例子中,我们首先为Int类型添加了四个计算型属性,分别是plus100、minus10、times10和divide5。然后,我们又添加了一个calculate方法,该方法接受一个运算符和一个值,并返回运算后的结果。最后,我们又添加了四个方法,分别是add、subtract、multiply和divide,这些方法接受一个值并返回运算后的结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)