Swift语法笔记

栏目: Swift · 发布时间: 5年前

内容简介:默认情况下不需要加类型,有类型推导。如果需要指定类型,可以这么写:

类型

  • 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 关键字

范型

  • 用尖括号来表示范型

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Artificial Intelligence

Artificial Intelligence

Stuart Russell、Peter Norvig / Pearson / 2009-12-11 / USD 195.00

The long-anticipated revision of this #1 selling book offers the most comprehensive, state of the art introduction to the theory and practice of artificial intelligence for modern applications. Intell......一起来看看 《Artificial Intelligence》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具