它除了借鉴语言如C,Swift是苹果推出的一个相比新的言语

这种Swift语言也具有很多这种脚本语法的特点,这种Swift语言也具有很多这种脚本语法的特点

Swift是苹果推出的一个比较新的言语,它除了借鉴语言如C#、Java等情节外,好像还利用了重重JavaScript脚本里面的部分剧本语法,用起来感到相当棒,作为一个使用C#连年的技术控,对那种相比较超前的言语分外感兴趣,从前也在就学ES6语法的时候学习了阮一峰的《ECMAScript
6
入门
》,对JavaScript脚本的ES6语法写法叹为观止,那种Swift语言也不无许多那种本子语法的风味,可以说那一个Swift在收到了Object
C的长处并丢掉一些不佳的东西外,同时收到了多量新一代语言的种种特色,包涵泛型、元祖等风味。我在念书Swift的时候,发现合法的语言介绍小说(The
Swift Programming
Language
)依旧这几个浅显易懂,纵然是英文,然则代码及分析表达都很成功,就是内容显示比较多一些,而我辈作为技术人员,一般看代码就很好刺探了各个语法特点了,基于这几个缘故,我对官网的案例代码举行了一个摘要统计,以代码的法子进行斯威夫特语言的语法特点介绍,总计一句话就是:快看Sample代码,速学斯威夫特语言。

Swift是苹果推出的一个相比较新的言语,它除了借鉴语言如C#、Java等内容外,好像还利用了诸多JavaScript脚本里面的有些剧本语法,用起来倍感尤其棒,作为一个使用C#经年累月的技巧控,对那种相比超前的语言格外感兴趣,以前也在上学ES6语法的时候学习了阮一峰的《ECMAScript
6
入门
》,对JavaScript脚本的ES6语法写法叹为观止,那种Swift语言也装有许多那种本子语法的特色,可以说那一个Swift在接到了Object
C的独到之处并丢掉一些糟糕的事物外,同时吸收了汪洋新一代语言的各样风味,包罗泛型、元祖等特征。我在学习斯维夫特的时候,发现合法的言语介绍小说(The
Swift Programming
Language
)照旧尤其浅显易懂,固然是英文,不过代码及分析表达都很到位,就是内容呈现比较多一些,而大家作为技术人员,一般看代码就很好刺探了各类语法特点了,基于这些原因,我对官网的案例代码进行了一个摘要统计,以代码的不二法门展开斯威夫特语言的语法特点介绍,统计一句话就是:快看萨姆ple代码,速学Swift语言。

1、语法速览

var myVariable = 42
myVariable = 50
let myConstant = 42

变量定义用var,常量则用let,类型自行估量。

 

let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

用括号包括变量

 

let quotation = """
I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) pieces of fruit."
"""

代码通过五个双引号来含有预订格式的字符串(包罗换行符号),左边缩进空格省略。

 

var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"

var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

数组和字典集合伊始化符合常规,字典后边能够保存逗号结尾

let emptyArray = [String]()
let emptyDictionary = [String: Float]()

初阶化函数也相比较精简。

 

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
print(teamScore)

控制流的if-else这个和其余语言没有啥样差别,for … in
则是迭代遍历的语法,控制流格局还帮助任何的while、repeat…while等不等的语法。

 

var optionalString: String? = "Hello"
print(optionalString == nil)

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}

这一部分则是可空类型的采纳,以及可空判断语句的施用,可空判断语句在Swift中行使尤其广阔,那种相当于先求值再判断是不是进入大括符语句。

 

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.")
}

Switch语法和常规的语言不一样,那种简化了一些语法,各种子条件不用显式的写break语句(默许就是回来的),多个条件逗号分开即可公用一个判定处理。

 

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

地点字典遍历的措施拔取for…in的措施展开遍历,此外通过(kind, numbers)的艺术开展一个参数的解构进度,把字典的键值分别交由kind,numbers那八个参数。

 

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

上面的for…in循环利用了一个语法符号..<属于数学半封闭概念,从0到4,不含4,同理还有全封闭符号:…全包括左右多个范围的值。

 

func greet(person: String, day: String) -> String {
    return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")

地方是函数的概念,以func关键字定义,括号内是参数的价签、名称和体系内容,再次回到值通过->指定。

地点函数要求输入参数名称,假若不要求参数名称,可以经过下划线省略输入,如下

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

除此以外参数名称可以采用标签名称。

func greet(person: String, from hometown: String) -> String {
    return "Hello \(person)!  Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino"))
// Prints "Hello Bill!  Glad you could visit from Cupertino."

嵌套函数如下所示。

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

复杂一点的函数的参数可以流传函数进行应用,那种接近闭包的处理了

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)

下边是一个闭包的函数,闭包通过in 来分别参数和再次来到的函数体

numbers.map({ (number: Int) -> Int in
    let result = 3 * number
    return result
})

 

 

class Shape {
    var numberOfSides = 0
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

类的概念通过class关键字展开标识,默许的权杖是internal,在类型模块内部可以访问的,非常有利。

拔取则如下所示,可以因而点语法直接获得属性和调用方法。

var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

 

class NamedShape {
    var numberOfSides: Int = 0
    var name: String

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

    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

类经过选择init的指定名称作为构造函数,使用deinit来做析构函数,使用self来得到当前的类引用,类似于此外语言的this语法,super获取基类的引用。

其余的处理格局如继续、重写的语法和C#类似。

class Square: NamedShape {
    var sideLength: Double

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

    func area() -> Double {
        return sideLength * sideLength
    }

    override func simpleDescription() -> String {
        return "A square with sides of length \(sideLength)."
    }
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()

 

类的习性使用get、set语法关键字,和C#类似

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
        }
    }

 

class TriangleAndSquare {
    var triangle: EquilateralTriangle {
        willSet {
            square.sideLength = newValue.sideLength
        }
    }
    var square: Square {
        willSet {
            triangle.sideLength = newValue.sideLength
        }
    }

类属性的赋值可以拓展考察,如通过willSet在设置以前调用,didSet在安装之后调用,完毕对品质值得监控处理。

 

enum Rank: Int {
    case ace = 1
    case two, three, four, five, six, seven, eight, nine, ten
    case jack, queen, king
    func simpleDescription() -> String {
        switch self {
        case .ace:
            return "ace"
        case .jack:
            return "jack"
        case .queen:
            return "queen"
        case .king:
            return "king"
        default:
            return String(self.rawValue)
        }
    }
}
let ace = Rank.ace
let aceRawValue = ace.rawValue

和类及其余类型一样,枚举类型在斯维夫特中仍是可以有主意定义,是一种卓殊灵活的类型定义,那一个和我们后边接触过的相似语言有所差距。

enum ServerResponse {
    case result(String, String)
    case failure(String)
}

let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese.")

switch success {
case let .result(sunrise, sunset):
    print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
    print("Failure...  \(message)")
}

 

struct Card {
    var rank: Rank
    var suit: Suit
    func simpleDescription() -> String {
        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
    }
}
let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()

布局类型和类的各类方面很相近,结构援救构造函数,方法定义,属性等,紧要一点见仁见智是协会在代码传递的是副本,而类实例传递的是类的引用。

 

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

此间的商事,类似很多言语的接口概念,但是比正常语言(包涵C#)的接口更加多种化、复杂化一些。

斯威夫特的协议,可以有一些方法已毕,协议得以可选,继承其余协商等等。

 

extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}
print(7.simpleDescription)

推而广之函数通过extension举行标识,可以为已有些类举行扩充部分奇特的点子处理,那几个类似C#的扩展函数。

 

func send(job: Int, toPrinter printerName: String) throws -> String {
    if printerName == "Never Has Toner" {
        throw PrinterError.noToner
    }
    return "Job sent"
}

卓殊处理中,函数注解通过throws关键字标识有极度抛出,在函数里面通过throw进行卓殊抛出处理。

而在拍卖有格外的地点开展阻挠,则经过do…catch的点子开展拍卖,在do的语句里面,通过try来堵住大概出现的不得了,默认catch里面的相当名称为error。

do {
    let printerResponse = try send(job: 1040, toPrinter: "Bi Sheng")
    print(printerResponse)
} catch {
    print(error)
}

可以对两个特别进行判断处理

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")
let printerFailure = try? send(job: 1885, toPrinter: "Never Has Toner")

 

var fridgeIsOpen = false
let fridgeContent = ["milk", "eggs", "leftovers"]

func fridgeContains(_ food: String) -> Bool {
    fridgeIsOpen = true
    defer {
        fridgeIsOpen = false
    }

    let result = fridgeContent.contains(food)
    return result
}
fridgeContains("banana")
print(fridgeIsOpen)

动用defer的首要字来在函数再次回到前处理代码块,假使有多个defer函数,则是后进先出的措施开展调用,最后的defer先调用,依次倒序。

 

func makeArray<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] {
    var result = [Item]()
    for _ in 0..<numberOfTimes {
        result.append(item)
    }
    return result
}
makeArray(repeating: "knock", numberOfTimes: 4)

斯威夫特支持泛型,由此可以大大简化很多函数的编撰,提供越来越强硬的意义。

enum OptionalValue<Wrapped> {
    case none
    case some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .none
possibleInteger = .some(100)

 

func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool
    where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
        for lhsItem in lhs {
            for rhsItem in rhs {
                if lhsItem == rhsItem {
                    return true
                }
            }
        }
        return false
}
anyCommonElements([1, 2, 3], [3])

泛型的参数支持where的首要性字展开泛型类型的束缚,如可以指定泛型的参数拔取什么协议可能接续哪个基类等等。

 

1、语法速览

var myVariable = 42
myVariable = 50
let myConstant = 42

变量定义用var,常量则用let,类型自行估计。

 

let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

用括号包括变量

 

let quotation = """
I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) pieces of fruit."
"""

代码通过七个双引号来含有预订格式的字符串(包罗换行符号),左侧缩进空格省略。

 

var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"

var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

数组和字典集合开首化符合常规,字典前面能够保存逗号结尾

let emptyArray = [String]()
let emptyDictionary = [String: Float]()

先导化函数也相比较精简。

 

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
print(teamScore)

控制流的if-else那一个和其他语言没有何样异样,for … in
则是迭代遍历的语法,控制流形式还匡助任何的while、repeat…while等不等的语法。

 

var optionalString: String? = "Hello"
print(optionalString == nil)

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}

那有些则是可空类型的运用,以及可空判断语句的行使,可空判断语句在Swift中选拔越发常见,那种相当于先求值再判断是还是不是进入大括符语句。

 

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.")
}

Switch语法和正常的语言分化,那种简化了有些语法,每一个子条件不用显式的写break语句(默许就是回去的),多个原则逗号分开即可公用一个论断处理。

 

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

地点字典遍历的主意使用for…in的主意展开遍历,其余通过(kind, numbers)的法门举办一个参数的解构进度,把字典的键值分别交由kind,numbers那七个参数。

 

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

地点的for…in循环利用了一个语法符号..<属于数学半封闭概念,从0到4,不含4,同理还有全封闭符号:…全包蕴左右多个范围的值。

 

func greet(person: String, day: String) -> String {
    return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")

位置是函数的概念,以func关键字定义,括号内是参数的价签、名称和体系内容,再次来到值通过->指定。

下边函数须要输入参数名称,即使不需求参数名称,可以通过下划线省略输入,如下

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

此外参数名称可以运用标签名称。

func greet(person: String, from hometown: String) -> String {
    return "Hello \(person)!  Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino"))
// Prints "Hello Bill!  Glad you could visit from Cupertino."

嵌套函数如下所示。

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

复杂一点的函数的参数可以流传函数进行利用,那种接近闭包的处理了

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)

上边是一个闭包的函数,闭包通过in 来分裂参数和再次来到的函数体

numbers.map({ (number: Int) -> Int in
    let result = 3 * number
    return result
})

 

 

class Shape {
    var numberOfSides = 0
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

类的概念通过class关键字展开标识,默许的权能是internal,在类型模块内部可以访问的,相当方便。

运用则如下所示,能够通过点语法直接获得属性和调用方法。

var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

 

class NamedShape {
    var numberOfSides: Int = 0
    var name: String

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

    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

类经过使用init的指定名称作为构造函数,使用deinit来做析构函数,使用self来博取当前的类引用,类似于其余语言的this语法,super获取基类的引用。

其它的处理格局如继续、重写的语法和C#类似。

class Square: NamedShape {
    var sideLength: Double

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

    func area() -> Double {
        return sideLength * sideLength
    }

    override func simpleDescription() -> String {
        return "A square with sides of length \(sideLength)."
    }
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()

 

类的习性使用get、set语法关键字,和C#类似

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
        }
    }

 

class TriangleAndSquare {
    var triangle: EquilateralTriangle {
        willSet {
            square.sideLength = newValue.sideLength
        }
    }
    var square: Square {
        willSet {
            triangle.sideLength = newValue.sideLength
        }
    }

类属性的赋值可以进行观看,如通过willSet在设置此前调用,didSet在安装之后调用,落成对质量值得监控处理。

 

enum Rank: Int {
    case ace = 1
    case two, three, four, five, six, seven, eight, nine, ten
    case jack, queen, king
    func simpleDescription() -> String {
        switch self {
        case .ace:
            return "ace"
        case .jack:
            return "jack"
        case .queen:
            return "queen"
        case .king:
            return "king"
        default:
            return String(self.rawValue)
        }
    }
}
let ace = Rank.ace
let aceRawValue = ace.rawValue

和类及其余连串一样,枚举类型在斯维夫特中还足以有法子定义,是一种极度灵活的类型定义,那一个和大家此前接触过的形似语言有所差别。

enum ServerResponse {
    case result(String, String)
    case failure(String)
}

let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese.")

switch success {
case let .result(sunrise, sunset):
    print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
    print("Failure...  \(message)")
}

 

struct Card {
    var rank: Rank
    var suit: Suit
    func simpleDescription() -> String {
        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
    }
}
let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()

布局类型和类的各类方面很相近,结构匡助构造函数,方法定义,属性等,首要一点不一是结构在代码传递的是副本,而类实例传递的是类的引用。

 

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

此间的商谈,类似很多语言的接口概念,但是比正规语言(包罗C#)的接口越发五种化、复杂化一些。

Swift的协商,可以有局地方法达成,协议得以可选,继承其他协商等等。

 

extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}
print(7.simpleDescription)

增添函数通过extension举办标识,能够为已有的类进行伸张部分独特的主意处理,那几个类似C#的扩展函数。

 

func send(job: Int, toPrinter printerName: String) throws -> String {
    if printerName == "Never Has Toner" {
        throw PrinterError.noToner
    }
    return "Job sent"
}

极度处理中,函数声明通过throws关键字标识有特别抛出,在函数里面通过throw举办尤其抛出处理。

而在拍卖有不行的地点开展拦截,则透过do…catch的法门举行拍卖,在do的讲话里面,通过try来阻止只怕出现的可怜,默许catch里面的可怜名称为error。

do {
    let printerResponse = try send(job: 1040, toPrinter: "Bi Sheng")
    print(printerResponse)
} catch {
    print(error)
}

可以对五个要命举行判定处理

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")
let printerFailure = try? send(job: 1885, toPrinter: "Never Has Toner")

 

var fridgeIsOpen = false
let fridgeContent = ["milk", "eggs", "leftovers"]

func fridgeContains(_ food: String) -> Bool {
    fridgeIsOpen = true
    defer {
        fridgeIsOpen = false
    }

    let result = fridgeContent.contains(food)
    return result
}
fridgeContains("banana")
print(fridgeIsOpen)

动用defer的基本点字来在函数重临前处理代码块,假诺有多少个defer函数,则是后进先出的模式开展调用,最终的defer先调用,依次倒序。

 

func makeArray<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] {
    var result = [Item]()
    for _ in 0..<numberOfTimes {
        result.append(item)
    }
    return result
}
makeArray(repeating: "knock", numberOfTimes: 4)

Swift援助泛型,因而可以大大简化很多函数的编写,提供越来越强有力的功用。

enum OptionalValue<Wrapped> {
    case none
    case some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .none
possibleInteger = .some(100)

 

func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool
    where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
        for lhsItem in lhs {
            for rhsItem in rhs {
                if lhsItem == rhsItem {
                    return true
                }
            }
        }
        return false
}
anyCommonElements([1, 2, 3], [3])

泛型的参数支持where的根本字展开泛型类型的羁绊,如可以指定泛型的参数拔取什么样协议或然接续哪个基类等等。