博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Swift a tour
阅读量:6250 次
发布时间:2019-06-22

本文共 4171 字,大约阅读时间需要 13 分钟。

Use three double quotes (""") for strings that take up multiple lines

使用三个双引号,标示跨越多行的字符串

let quotation = """Even though there's whitespace to the left,the actual lines aren't indented.Except for this line.Double quotes (") can appear without being escaped. I still have \(apples + oranges) pieces of fruit."""

Another way to handle optional values is to provide a default value using the ?? operator. If the optional value is missing, the default value is used instead.

另外一种处理可选值的方式是用 ?? 运算符 如果一个可选值不存在值,则使用默认值代替

let nickName: String? = nillet fullName: String = "John Appleseed"let informalGreeting = "Hi \(nickName ?? fullName)"

Notice how let can be used in a pattern to assign the value that matched the pattern to a constant.

可以使用let 在switch里进行一个模式匹配
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.")}

In an if statement, the conditional must be a Boolean expression—this means that code such as if score { ... } is an error, not an implicit comparison to zero. 与0没有什么关系

You use for-in to iterate over items in a dictionary by providing a pair of names to use for each key-value pair. Dictionaries are an unordered collection, so their keys and values are iterated over in an arbitrary order.

(key, value)

let interestingNumbers = [    "Prime": [2, 3, 5, 7, 11, 13],    "Fibonacci": [1, 1, 2, 3, 5, 8],    "Square": [1, 4, 9, 16, 25],]var largest = 0for (kind, numbers) in interestingNumbers {    for number in numbers {        if number > largest {            largest = number        }    }}print(largest)

Use while to repeat a block of code until a condition changes. The condition of a loop can be at the end instead, ensuring that the loop is run at least once.

类似do while

var m = 2repeat {    m *= 2} while m < 100print(m)

You can keep an index in a loop by using ..< to make a range of indexes.

Use ..< to make a range that omits its upper value, and use ... to make a range that includes both values.

var total = 0for i in 0..<4 {    total += i}print(total)

By default, functions use their parameter names as labels for their arguments. Write a custom argument label before the parameter name, or write _ to use no argument label.

参数的外部名称和内部名称

func greet(_ person: String, on day: String) -> String {    return "Hello \(person), today is \(day)."}greet("John", on: "Wednesday")

tuple 下标从0开始

Use a tuple to make a compound value—for example, to return multiple values from a function. The elements of a tuple can be referred to either by name or by number.

func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {    var min = scores[0]    var max = scores[0]    var sum = 0        for score in scores {        if score > max {            max = score        } else if score < min {            min = score        }        sum += score    }        return (min, max, sum)}let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])print(statistics.sum)print(statistics.2)

函数可以嵌套

Functions can be nested. Nested functions have access to variables that were declared in the outer function. You can use nested functions to organize the code in a function that is long or complex.

func returnFifteen() -> Int {    var y = 10    func add() {        y += 5    }    add()    return y}returnFifteen()

Functions are a first-class type. This means that a function can return another function as its value.

函数本身可以作为一种类型返回,非常灵活
func makeIncrementer() -> ((Int) -> Int) {    func addOne(number: Int) -> Int {        return 1 + number    }    return addOne}var increment = makeIncrementer()increment(7)

A function can take another function as one of its arguments.

当然也能作为参数

func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {    for item in list {        if condition(item) {            return true        }    }    return false}func lessThanTen(number: Int) -> Bool {    return number < 10}var numbers = [20, 19, 7, 12]hasAnyMatches(list: numbers, condition: lessThanTen)

转载地址:http://gqfsa.baihongyu.com/

你可能感兴趣的文章
tensorflow安装
查看>>
【老叶茶馆】MySQL复制中slave延迟监控
查看>>
android onPause OnSavedInstance
查看>>
[PHP] - Laravel - CSRF token禁用方法
查看>>
python的序列类
查看>>
分享在MVC3.0中使用jQue“.NET研究”ry DataTable 插件
查看>>
使用Lombok插件需要注意的问题
查看>>
2018-2019-2 20165232 《网络对抗技术》 Exp6 信息搜集与漏洞扫描
查看>>
Visual Studio中“后期生成事件命令行” 中使用XCopy命令
查看>>
代码导读
查看>>
Atlas读写分离[高可用]
查看>>
shell实现rpm -e 一键卸载所有相关包以及依赖
查看>>
坦克大战中摄像机的设置
查看>>
ros:出现:error: ros/ros.h: No such file or directory
查看>>
Java坦克大战 (四) 之子弹的产生
查看>>
web 中常用的两种上传文件的方法总结
查看>>
SCVMM 2012 简体中文正式版部署手册
查看>>
BZOJ 3097: Hash Killer I【构造题,思维题】
查看>>
C/C++中int128的那点事
查看>>
ios多线程学习笔记(2)
查看>>