语法速览

斯威夫特是苹果推出的2个比较新的语言,它除了借鉴语言如C#、Java等内容外,好像还选择了无数JavaScript脚本里面的一些本子语法,用起来感觉相当厉害,作为1个使用C#连年的技术控,对那种相比较超前的言语相当感兴趣,以前也在学习ES6语法的时候学习了阮一峰的《ECMAScript
6
入门
》,对JavaScript脚本的ES6语法写法惊叹不已,那种斯威夫特语言也负有众多那种本子语法的特点,能够说那几个Swift在接到了Object
C的独到之处并丢掉一些倒霉的事物外,同时收纳了汪洋新一代语言的各样风味,包括泛型、元祖等特征。作者在求学Swift的时候,发现合法的言语介绍小说(The
Swift Programming
Language
)照旧特别浅显易懂,纵然是英文,但是代码及分析表达都很成功,正是内容呈现相比较多一些,而我辈作为技术人员,一般看代码就很好刺探了各样语法特点了,基于那一个缘故,笔者对官网的案例代码实行了八个摘要总结,以代码的不二法门开始展览Swift语言的语法特点介绍,计算一句话正是:快看Sample代码,速学斯威夫特语言。

斯维夫特是苹果推出的多少个比较新的语言,它除了借鉴语言如C#、Java等内容外,好像还使用了过多JavaScript脚本里面包车型大巴一部分本子语法,用起来倍感尤其棒,作为2个使用C#经年累月的技巧控,对那种对比超前的言语相当感兴趣,在此之前也在就学ES6语法的时候学习了阮一峰的《ECMAScript
6
入门
》,对JavaScript脚本的ES6语法写法赞叹不已,那种斯威夫特语言也具备众多这种本子语法的风味,能够说那个斯维夫特在吸收接纳了Object
C的亮点并丢掉一些不佳的东西外,同时接收了多量新一代语言的各类风味,包涵泛型、元祖等特征。笔者在读书斯维夫特的时候,发现合法的言语介绍小说(The
Swift Programming
Language
)依然要命浅显易懂,纵然是英文,不过代码及分析表明都很成功,正是内容展现比较多一些,而小编辈作为技术职员,一般看代码就很好刺探了各样语法特点了,基于那些缘故,小编对官网的案例代码进行了1个摘要计算,以代码的点子展开斯威夫特语言的语法特点介绍,总括一句话正是:快看Sample代码,速学斯维夫特语言。

① 、语法速览

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

这一部分则是可空类型的接纳,以及可空判断语句的施用,可空判断语句在斯威夫特中央银行使分外广阔,那种约等于先求值再判断是或不是进入大括符语句。

 

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)

上面是2个闭包的函数,闭包通过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

和类及其余门类一样,枚举类型在Swift中还足以有措施定义,是一种万分灵活的类型定义,这几个和我们以前接触过的形似语言有所差异。

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?的章程开始展览温馨的特别处理,假诺有12分重临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的重中之重字展开泛型类型的约束,如能够钦赐泛型的参数选择什么样协议或然接续哪个基类等等。

 

一 、语法速览

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)的不二法门展开3个参数的解构进程,把字典的键值分别交由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

和类及其余品种一样,枚举类型在Swift中还能够有方法定义,是一种拾分灵活的类型定义,那个和大家后边接触过的相似语言有所出入。

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)

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的首要字展开泛型类型的羁绊,如能够钦命泛型的参数接Nash么样协议大概连续哪个基类等等。