惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 三生石上(FineUI控件)
Blog — PlanetScale
Blog — PlanetScale
B
Blog
GbyAI
GbyAI
爱范儿
爱范儿
月光博客
月光博客
N
Netflix TechBlog - Medium
T
Tailwind CSS Blog
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
Vercel News
Vercel News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
WordPress大学
WordPress大学
The GitHub Blog
The GitHub Blog
Recent Announcements
Recent Announcements
腾讯CDC
MyScale Blog
MyScale Blog
V
Visual Studio Blog
The Cloudflare Blog
Microsoft Security Blog
Microsoft Security Blog
A
About on SuperTechFans
Google DeepMind News
Google DeepMind News
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

Jiajun的技术笔记

你好,2026! TiDB 源码阅读(六):TiDB Coprocessor 源码解析 性能优化的核心思想 TiDB 源码阅读(五):索引 TiDB 源码阅读(四):AST、逻辑计划、物理计划 CockroachDB Serverless Architecture podman 无故退出 Cursor Control-L (CTRL-L) Keyboard Shortcuts in Terminal Replace docker with podman Using xmonad with xfce4 A RC script for freebsd frpc 自己动手写一个k8s controller AI 会取代你的(编程)岗位吗? 自建DERP服务器提升Tailscale连接速度(使用Nginx转发) 自动升级Docker容器 再读《程序员修炼之道-从小工到专家》 让浏览器下载文件 再读《软件随想录》/《黑客与画家》/《软技能》 HTTP 压力测试中的 Coordinated Omission 2的补码 编程语言中的 context 是什么? flutter macOS 构建出错 Flatpak 使用小记 Golang CAS 操作是怎么实现的 PostgreSQL 当MQ来使用 Clash 结合 工作VPN 的网络设计 使用 PostgreSQL 搭建 JuiceFS PostgreSQL 配置优化和日志分析 有GitHub Copilot?那就可以搭建你的ChatGPT4服务 窗口函数的使用(以PG为例)
Swift语法笔记
Jiajun Huang · 2019-06-25 · via Jiajun的技术笔记

类型

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

范型

  • 用尖括号来表示范型

相关文章