import UIKit

extension Double {

    var km: Double { return self * 1_000.}
var m : Double { return self}
var cm: Double { return self / 100.0}
var mm: Double { return self / 1_000.}
var ft: Double { return self / 3.28084}
} extension Int {
mutating func square() {
self = self * self
}
} extension Int {
subscript(digitIndex: Int) -> Int {
var decimalBase =
for _ in ..<digitIndex {
decimalBase *=
}
return (self / decimalBase) %
}
} extension Int {
enum Kind {
case Negative, Zero, Positive
}
var kind: Kind {
switch self {
case :
return .Zero
case let x where x > :
return .Positive
default:
return .Negative
} }
} class First_Demo4: UIViewController { override func viewDidLoad() {
super.viewDidLoad() self.navigationItem.title = "扩展语法"
self.view.backgroundColor = UIColor.white let oneInch = 25.4.mm
print("one inch is \(oneInch) meters")
// 打印 “One inch is 0.0254 meters”
let threeFeet = .ft
print("Three feet is \(threeFeet) meters")
// 打印 “Three feet is 0.914399970739201 meters”
let aMarathon = .km + .m
print("A marathon is \(aMarathon) meters long")
// 打印 “A marathon is 42195.0 meters long” /*
通过扩展添加的实例方法也可以修改该实例本身。结构体和枚举类型中修改 self 或其属性的方法必须将该实例,
方法标注为 mutating ,正如来自原始实现的可变方法一样。
*/
var someInt =
someInt.square()
print(someInt)
// someInt 的值现在是 9 print([]) // 返回 5
print([]) // 返回 9
print("-------------我是分割线----------------") //判断正负
/*
函数 printIntegerKinds(_:) 接受一个 Int 数组,然后对该数组进行迭代。
在每次迭代过程中,对当前整数 的计算型属性 kind 的值进行评估,并打印出适当的描述。
*/
printIntegerKinds([, , -, , -, , ]) } override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
} func printIntegerKinds(_ numbers: [Int]) {
for number in numbers {
switch number.kind {
case .Negative:
print("- ", terminator: "")
case .Zero:
print("0 ", terminator: "")
case .Positive:
print("+ ", terminator: "")
}
}
print("")
} }
05-02 23:30