Swift语法入门

本文简要介绍下 Swift 的基本语法。

  • 导入 package
import Foundation
  • 变量和常量
var str1 = "Hello, playground"
let str2 = "test"
  • 数组
var myArray = [
    "t1",
    "t2",
    "t3"
]
  • 集合
let ttt: Set = [0, 1, 2, 3, 6, 9, 90, 2]
  • 字典
var myDict = [
    "k1": "v1",
    "k2": "v2",
    "k3": "v3"
]
  • 方法
func test(_ value: Int) -> Bool {
    if value > 10 {
        return true
    }

    // 编译错误,Swift强制if语句加{}
    //    if value > 10
    //        return true

    return false
}
  • 多重返回值函数
func test1(_ value: Int) -> (errorCode: Int, errorDes: String) {
    if value > 10 {
        return (200, "Success")
    }

    return (404, "Not Found")
}

let r = test(100)
let r1 = test1(90)
print("result1 = (\(r1.0), \(r1.1))")
print("result1 = (\(r1.errorCode), \(r1.errorDes))")
  • 区间运算符
// 闭区间运算符(a...b)定义一个包含从a到b(包括a和b)的所有值的区间,b必须大于a。
for index in 1...5 {
    print("index = \(index)")
}
// 半开区间运算符
for index in 1..<5 {
    print("index = \(index)")
}
  • 闭包
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

func backwards(s1: String, s2: String) -> Bool {
    return s1 > s2
}

func closureTest(_ param1: Int, param2: (_ s1: String, _ s2: String) -> Bool) {
    print("param1 = \(param1), param2 = \(param2("d", "b"))")
}

closureTest(1, param2: backwards)
closureTest(2, param2: {
    (s1: String, s2: String) -> Bool in

    return s1 < s2
})
closureTest(3, param2: {
    (s1, s2) in // 类型可自动推倒出来

    return s1 < s2
})
closureTest(4, param2: {(s1, s2) in return s1 < s2})
closureTest(5, param2: {$0 > $1})
// 运算符函数
closureTest(6, param2: >)
  • 尾随闭包
func trailingClosuresTest(_ param: () -> ()) {
    print("trailingClosuresTest 1")

    param()

    print("trailingClosuresTest 2")
}

// 以下是不使用尾随闭包进行函数调用
trailingClosuresTest({
    () -> () in

    print("trailingClosuresTest 3")
})
trailingClosuresTest({
    print("trailingClosuresTest 4")
})

// 以下是使用尾随闭包进行函数调用
trailingClosuresTest() {
    print("trailingClosuresTest 5")
}

// 如果函数只需要闭包表达式一个参数,当使用尾随闭包时,甚至可以把()省略掉。
trailingClosuresTest {
    print("trailingClosuresTest 6")
}
  • 捕获值
func makeIncrementor(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 1
    func incrementor() -> Int {
        runningTotal += amount
        return runningTotal
    }
    return incrementor
}

let capture1 = makeIncrementor(forIncrement: 9)
print(capture1())
print(capture1())

print 输出如下:

10
19

  • 枚举
enum Barcode {
    case UPCA(Int, Int, Int)
    case QRCode(String)
}

func enumTest(value: Barcode) {
    switch(value) {
    case Barcode.UPCA(let numberSystem, let identifier, let check):
        print("UPCA numberSystem = \(numberSystem), identifier = \(identifier), check = \(check)")
    case Barcode.QRCode(let productCode):
        print("QRCode productCode = \(productCode)")
    }
}

enumTest(Barcode.QRCode("qs"))
enumTest(Barcode.UPCA(1, 2, 3))

enum Planet: Int {
    case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

enum StrEnum: String {
    case T1 = "a"
    case T2 = "b"
}
  • 计算属性
struct Point {
    var x = 0.0
    var y = 0.0
}
struct Size {
    var width = 0.0
    var height = 0.0
}
struct Rect {
    var origin = Point()
    var size = Size()
    var center: Point {
        get {
            let centerX = origin.x + (size.width / 2.0)
            let centerY = origin.y + (size.height / 2.0)

            return Point(x: centerX, y: centerY)
        }

        set {
            origin.x = newValue.x - (size.width / 2.0)
            origin.y = newValue.y - (size.height / 2.0)
        }
    }
}

var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0))
print("square.center = \(square.center)")
square.center = Point(x: 15.0, y: 15.0)
print("square origin = \(square.origin)")

print 输出如下:

square.center = Point(x: 5.0, y: 5.0)
square origin = Point(x: 10.0, y: 10.0)

  • 属性观察器
class StepCounter {
    var totalSteps: Int = 0 {

        willSet(newTotalSteps) {
            print("1 totalSteps = \(totalSteps)")
        }
        didSet {

            if(totalSteps > oldValue) {
                print("2 totalSteps = \(totalSteps)")
            }
        }
    }
}

let stepCounter = StepCounter()
stepCounter.totalSteps = 100

print 输出如下:

1 totalSteps = 0
2 totalSteps = 100

  • 结构体
struct PointTest {
    var x = 0.0
    var y = 0.0
    mutating func moveBy(deltaX: Double, deltaY: Double) {
        x += deltaX
        y += deltaY
    }
}

使用 mutating 关键字是为了能在该方法中修改 struct 的变量。

  • 构造、析构、! 、?
class Player {
    init() {
        print("Player init")
    }

    deinit {
        print("Player deinit")
    }

    func test() {

    }
}

var player: Player? = Player()    // 调用构造方法

if(nil != player) {
    player!.test()
}
// 等价于上面这种情况
player?.test()

player = nil    // 调用析构方法
  • 继承 - 单继承,多实现
class A {

}

class B: A {

}

protocol IA {

}

protocol IB {

}

protocol IC {

}

class C: A, IA, IB, IC {

}
  • extension
extension Double {
    var km: Double { return self * 1_000.0 }
    var m : Double { return self }
    var cm: Double { return self / 100.0 }
    var mm: Double { return self / 1_000.0 }
    var ft: Double { return self / 3.28084 }
}

let t = 45.7.km
print(t)

print 输出如下:

45700.0

发表评论

电子邮件地址不会被公开。 必填项已用*标注