Swift语法笔记

类型

  • Int
  • Double
  • Float
  • Bool
  • String
  • Array
  • Tuple
  • Set
  • Dictionary

类型别名

  • 使用 typealias 来声明类型别名

变量

  • let 声明常量
  • var 声明变量

默认情况下不需要加类型,有类型推导。如果需要指定类型,可以这么写:let myVar: Double = 2

  • 还可以使用 \() 在字符串里进行运算,例如:
let apples = 3
let oranges = 4

print("\(apples) apples and \(oranges) oranges")
  • 用三引号来包含换行的字符串。
let words = """
hello world
    world hello

hello world
world hello
    this that
"""

print(words)
  • 使用中括号来创建数组和字典/哈希表:
var shoppingList = ["catfish", "water", "tulips"]
shoppingList[1] = "bottle of water"

var aDict: [String: Any] = [
    "hello": "world",
    "this": 1,
]

print(shoppingList, aDict)
  • 如果要创建控字典或者数组:
let emptyArray = [String]()
let emptyDictionary = [String: Float]()

// 或者这样,当然只有在类型信息可以推导出来的时候才能这样
shoppingList = []
occupations = [:]

控制流

  • 可以使用 for... in..., while..., repeat...while... 来进行循环。循环变量可以不写括号(当然也可以写)
  • if 后面只能接bool值,同时也可以接一个 let,用于判断值是否为空
var shoppingList: [String?] = ["hello", nil, "world"]

for i in shoppingList {
    if let item = i {
        print(item)
    }
}
  • ?? 可以用来判断值是否为空,如果为空,就使用默认值,例如:
let nickName: String? = nil
let defaultNickname = "foo"

print("\(nickName ?? defaultNickname)")
  • switch...case... 语句:
let vegetable = "red pepper"
switch vegetable {
case "celery":
    print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
    print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
    print("Is it a spicy \(x)?")
default:
    print("Everything tastes good in soup.")
}
// Prints "Is it a spicy red pepper?"
  • ..<... 类似于Python中的range,前者不包括上界,后者包括上界:
for i in 0..<4 {
    print(i)
}

for i in 0...4 {
    print(i)
}

函数

  • 使用 func 关键字声明函数,-> 指示函数返回类型

面向对象

  • class 关键字用于声明类
class NamedShape {
    var name: String

    init(name: String) {
        self.name = name
    }

    func SayHi() -> String {
        return "Hello, I'm shape \(self.name)"
    }
}

print(NamedShape(name: "foo").SayHi())
  • init 是类的构造器,deinit 是析构器

  • gettersetter:

class EquilateralTriangle: NamedShape {
    var sideLength: Double = 0.0

    init(sideLength: Double, name: String) {
        self.sideLength = sideLength
        super.init(name: name)
        numberOfSides = 3
    }

    var perimeter: Double {
        get {
            return 3.0 * sideLength
        }
        set {
            sideLength = newValue / 3.0
        }
    }

    override func simpleDescription() -> String {
        return "An equilateral triangle with sides of length \(sideLength)."
    }
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
print(triangle.perimeter)
// Prints "9.3"
triangle.perimeter = 9.9
print(triangle.sideLength)
// Prints "3.3000000000000003"
  • 如果不需要 gettersetter,但是需要前置和后置动作,可以使用 willSet, didSet

错误处理

  • 使用 throw 来标记函数,表明这个函数可能会抛出异常
  • 使用 do...catch... 来捕捉异常
do {
    let printerResponse = try send(job: 1440, toPrinter: "Gutenberg")
    print(printerResponse)
} catch PrinterError.onFire {
    print("I'll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
    print("Printer error: \(printerError).")
} catch {
    print(error)
}
  • 也可以用 try? 来捕获异常,如果有异常,返回一个nil,否则,返回值: let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler")

  • swift 也有 defer 关键字

范型

  • 用尖括号来表示范型

更多文章


支付宝和微信赞赏

你的赞赏是我写作的动力😍(支持支付宝和微信)