• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Swift常用语法示例代码(一)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

此篇文章整理自我以前学习Swift时的一些练习代码,其存在的意义多是可以通过看示例代码更快地回忆Swift的主要语法。

如果你想系统学习Swift或者是Swift的初学者请绕路,感谢GithubThe Swift Programming Language开源翻译的中文版,感谢极客学院wiki提供的PDF版本。

代码和PDF版本上传至Github,有兴趣的可以下载下来试试。

SwiftTour

Base

var str = "Hello, World!"

print(str)

// 变量用var声明,常量用let声明,变量类型自动推断
// 可在变量后声明类型,用冒号分隔
var myVariable = 42
let myConstant = 42
myVariable = 50
let explictDouble: Double = 60

// 值永远不会被隐式转换为其他类型,需要转换必须采用显式转换
let label = "The width is "
let width = 94
let widthLabel = label + String(width)

// 更为常见的将值转换为字符串的方法
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples"
let fruitSummary = "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 emptyArray1 = [String]()
let emptyDictionary1 = [String: Float]()
let emptyArray2: [String] = []
let emptyDictionary2: [String: Float] = [:]

// 控制流,if和switch用于选择,for-in,for,while和repeat-while用于循环
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和let,处理值缺失判断
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello"
if let name = optionalName {
    greeting = "Hello, \(name)"
}

// Switch支持任意类型的数据以及各种比较操作
let vegetable = "red pepper"

switch vegetable {
case "celery" :
    print("Add some raisins and make ants on a log")
case "cucumber", "watercress" :
    print("That woould 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")
}

// 使用for-in遍历字典
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
var numberGroup: String = "Null"
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
            numberGroup = kind
        }
    }
}
print(numberGroup, largest)

// while循环
var n = 2
while n \< 100 {
    n = n * 2
}
print(n)

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

// 可以在循环中使用..\<来表示范围,包含上界使用...
var firstForLoop = 0
for i in 0..\<4 {
    firstForLoop += i
}
print(firstForLoop)

var secondForLoop = 0
for var i = 0; i \< 4; ++i {
    secondForLoop += i
}
print(secondForLoop)

函数

// 使用func来声明函数,尾置返回
func greet(name: String, day: String) -\>String {
    return "Hello \(name), today is \(day)"
}
greet("Bob", day: "Tuesday")

// 使用元组来让函数返回多个值
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([5, 3, 100, 3, 9])
print(statistics.sum)

// 函数可以带有可变个数的参数,这些参数在函数内表现为数组的形式
func sumOf(numbers: Int...)-\>Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
sumOf()
sumOf(42, 597, 12)

// 函数可以嵌套,被嵌套的函数可以访问外侧函数的变量
func returnFifteen()-\>Int {
    var y = 10
    func add() {
        y += 5
    }
    add()
    return y
}
print(returnFifteen())

// 函数是类型,也可以作为另外一个函数的返回值
func makeIncrementer()-\>(Int -\> Int) {
    func addOne(number: Int)->Int {
        return 1 + number
    }
    return addOne
}

var increment = makeIncrementer()
print(increment(7))

// 函数也可以当做参数传入另外一个函数
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(numbers, condition: lessThanTen)

//闭包就是嵌套的匿名函数,{  in }
let mappedNumbers = numbers.map({number in 3 \* number})
print(mappedNumbers)
let sortedNumbers = numbers.sort{$0 \< $1}
print(sortedNumbers)

类和对象

// 使用class和类名创建一个类
class Shape {
    var numberOfSides = 0
    func simpleDescription() ->String {
        return "A Shape with \(numberOfSides) sides"
    }
}

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

// 使用init创建构造器,使用deinit创建一个析构函数
class NameShape {
    var numberOfSides: Int = 0
    var name: String
    init(name: String) {
        self.name = name
    }
    func simpleDescription() ->String {
        return "A Shape with \(numberOfSides) sides"
    }
}

// 子类重写父类的方法需要用override标记
class Squre: NameShape {
    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 = Squre(sideLength: 5.2, name: "My test Square")
test.area()
test.simpleDescription()

// 类的getter和setter
class EquilateralTriangle: NameShape {
    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 triangel = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
print(triangel.perimeter)
triangel.perimeter = 9.9
print(triangel.sideLength)

// 不需要计算属性,仍然需要在设置新值之前或之后运行代码,使用willset和didset
// 确保三角形的边长综合正方形的边长相同
class TriangleAndSquare {
    var triangle: EquilateralTriangle {
        willSet {
            square.sideLength = newValue.sideLength
        }
    }
    var square: Squre {
        willSet {
            triangel.sideLength = newValue.sideLength
        }
    }
    init(size: Double, name: String) {
        square = Squre(sideLength: size, name: name)
        triangle = EquilateralTriangle(sideLength: size, name: name)
    }
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "Another tested Shape")
print(triangleAndSquare.square.sideLength)
print(triangleAndSquare.triangle.sideLength)
triangleAndSquare.triangle = EquilateralTriangle(sideLength: 30, name: "Other")
print(triangleAndSquare.triangle.sideLength)
print(triangleAndSquare.square.sideLength)

// 处理变量的可选值时,可以在操作前加?
let optionalSquare: Squre? = Squre(sideLength: 2.5, name: "Optional square")
let sideLength = optionalSquare?.sideLength
print(sideLength)

枚举和结构体

import Foundation

// 使用enum创建一个枚举,枚举可以包含方法
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.Ten
let aceRawValue = ace.rawValue
print(aceRawValue)
print(ace.simpleDescription())

// 使用init?(rawValue:)初始化构造器在原始值和枚举值之间进行转换
let c = Rank(rawValue: 34)
print(c)
if let convertedRank = Rank(rawValue: 3) {
    let threeDescription = convertedRank.simpleDescription()
}

// 可以不设置原始值,但系统会内部为枚举设置枚举值
enum Suit {
    case Spades, Hearts, Diamonds, Clubs
    func simpleDecription()->String {
        switch self {
        case .Spades:
            return "spades"
        case .Hearts:
            return "hearts"
        case .Diamonds:
            return "diamonds"
        case .Clubs:
            return "clubs"
        }
    }
}
let hearts = Suit.Hearts
let heartsDescription = hearts.simpleDecription()
print(heartsDescription)

// struct和class的区别是,结构体传值,类传引用
struct Card {
    var rank: Rank
    var suit: Suit
    func simpleDescription()->String {
        return "The \(rank.simpleDescription()) of \(suit.simpleDecription())"
    }
}
let threeOfSpades = Card(rank: .Three, suit: .Spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
print(threeOfSpadesDescription)

// 枚举成员的实例值
enum ServerResponse {
    case Result(String,String)
    case Error(String)
}
let success = ServerResponse.Result("6:00", "9:00")
let failure = ServerResponse.Error("Out of cheese")
let success1 = ServerResponse.Result("8:00", "9:00")
switch success1 {
case let .Result(sunrise, sunset):
    let serverReponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)"
    print(serverReponse)
case let .Error(error):
    let serverReponse = "Failure... \(error)"
    print(serverReponse)
}

协议

import Foundation

// 使用protocol来声明一个协议
protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

// 类、枚举和结构题都可以实现协议
class SimpleClass: ExampleProtocol {
    var simpleDescription: String = "A very simple class"
    var anotherProperty: Int = 69105
    func adjust() {
        simpleDescription += "Now 100% adjusted"
    }
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
print(aDescription)

// mutating关键字标记一个会修改结构体的方法
struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A very simple class"
    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
print(bDescription)

// 使用extension来为现有的类型添加功能
extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}
print(7.simpleDescription)

// 可以像使用其他类型一样使用协议名
// 即使protocolValue变量运行时类型是simpleClass,编译器会把它的类型当作ExampleProtocol
// 这意味着,不能调用类在它实现协议之外的方法或属性
let protocolValue: ExampleProtocol = a
print(protocolValue.simpleDescription)
// print(protocolValue.anotherProperty) //Error

泛型

import Foundation

// 在尖括号里写一个名字来创建一个泛型函数或类型
func repeatItem<Item>(item: Item, numberOfTimes: Int)-\>[Item] {
    var result = [Item]()
    for _ in 0..<numberOfTimes {
        result.append(item)
    }
    return result
}
let result = repeatItem("knock", numberOfTimes: 5)
print(result)

// 也可以穿件泛型函数、方法、类、枚举和结构体
enum OptionalValue<Wrapped> {
    case None
    case Some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(3)

// 在类型名后面使用where来指定对类型的需求
// 比如,限定类型实现某一个协议,限定两个类型是相同的,或者限定某个类必须有一个特定的父类
func anyCommonElements\<T: SequenceType, U: SequenceType where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element\>(lhs: T, \_ rhs: U)-\>Bool {
    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                return true
            }
        }
    }
    return false
}

print(anyCommonElements([1, 2 ,3], [3]))

SwiftBasics

SwiftBasics是对Swift类型和变量的介绍,有过别的语言基础的扫一眼即可。需要注意的地方主要是可选类型和元组,这是Swift特有的类型。

import Foundation

// Print(\_:,separator:,terminator:)
print("Hello World", "iOS",separator: "\*", terminator: "")

// 可以通过分号,实现一行写多条独立语句
let cat = "Tom"; print("Hello \(cat)")

// 可以访问不同整数类型的min和max属性来获取对应类型的最小值和最大值
// Swift中的Int长度与当前平台有关,在32位平台Int与Int32长度相同,在64位平台Int与Int64长度相同
print(Int8.max)
print(Int8.min)
print(Int.max)
print(Int64.max)

// 整数和浮点数都可以增加额外的零并且包含下划线,并不会影响字面值
let oneMillion = 001\_000\_000
print(oneMillion)

// 数值类型的转换需要调用类型内置构造器
// 可以通过扩展现有类型的构造器,使之接受更多的类型转换
let one:UInt8 = 1
let two:Int8 = 2
let onePlusTwo = one + UInt8(two)
print(onePlusTwo)

// 可以把多个值组合成一个复合值,元组内的值可以是任意类型,并不要求是相同类型
let http404Error = (404, "Not Found")
print(http404Error)

// 可以将一个元组的内容分解成单独的常量和变量
print("The status code is \(http404Error.0)")
let (statusCode, statusMessage) = http404Error
print("The status message is \(statusMessage)")
let (justTheStatusCode, \_) = http404Error
print("The status code is \(justTheStatusCode)")

// 在元组命名时对单个元素进行命名
let http200Status = (statusCode: 200, statusMessage: "OK")
print("The status code is \(http200Status.statusCode)")

// 可选类型
// 并不是所有对字符串都能转换为整数,Int构造器可能会失败,转换结果是可选类型
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
print(convertedNumber)

// 可以通过nil给可选类型变量赋值,nil不可以用于非可选类型
// 声明了一个可选类型变量没有赋值,系统会自动设置为nil
var serverReponseCode: Int? = 404
serverReponseCode = nil
var surveyAnswer: String?

// 可以使用相等不等符判断可选类型是否有值,当确定有值时,可以用!强制解析
if convertedNumber != nil {
    print("convertedNumber contains some integer value of \(convertedNumber!)")
}

// 可选绑定可以用在if和while语句中来对可选类型的值进行判断并把值赋给一个临时常量或变量
if let actualNumber = Int(possibleNumber) {
    print("\'\(possibleNumber)\' has an integer value of \(actualNumber)")
} else {
    print("\'\(possibleNumber)\' could not be converted to an integer")
}

// 可以包含多个可选绑定在if语句中,并使用where子句做布尔值判断
if let firstNumber = Int("4"), secondNumber = Int("42") where firstNumber \< secondNumber {
    print("\(firstNumber) < \(secondNumber)")
}

// 用!声明隐式解析可选类型
// 隐式可选类型其实就是一个普通的可选类型,但是可以被当作非可选类型来使用,并不需要每次都解析可选值
let possibleString: String? = "An optional string"
let forcedString: String = possibleString!
print(forcedString)
let assumedString: String! = "An implicitly unwrapped optional string"
let implicitString: String = assumedString
print(implicitString)

SwiftBasicOperators

SwiftBasicOperators部分是对Swift支持的运算符的介绍。Swift支持大部分标准C语言的运算符,且改进许多特性来减少常规编码错误。如赋值符(=)不返回值,算术运算符会检测并不允许溢出。区别于C语言,在Swift中,你可以对浮点数取余运算(%)。此外,Swift还提供了C语言中没有的区间运算符(a..\<b和a...b)。

import Foundation

// 如果赋值的右边是一个多元组,它的元素可以马上被分解成多个常量或变量
let (x, y) = (1, 2)
print(x, y)

// 取余运算,对负数b求余时,b的符号会被忽略
print(9 % 4)
print(-9 % 4)
print(9 % -4)

// 浮点数求余
print(8 % 2.5)

// 一元负号和一元正号运算符写在操作数之前,中间没有空格
// 注意的是,一元正号不做任何改变地返回操作数的值
let minusSix = -6
print(-minusSix)
print(+minusSix)

// 空合运算符 a ?? b
// 表达式a必须是Optional类型,b的类型必须与a的存储值类型一致
// 如果a为nil,则返回b的值。如果a有值,则返回a的解析值。
// 并不会改变a和b的值
let defaultColorName = "red"
var userDefinedColorName: String?
var colorNameToUse = userDefinedColorName ?? defaultColorName
print(colorNameToUse, userDefinedColorName)
userDefinedColorName = "grren"
colorNameToUse = userDefinedColorName ?? defaultColorName
print(colorNameToUse, userDefinedColorName)

// 区间运算符
for index in 1...5 {
    print("\(index) * 5 = \(index * 5)")
}
let names = ["Anna", "Alex", "Brain", "Jack"]
let count = names.count
for i in 0..\<count {
    print("第\(i)个人叫\(names[i])")
}

SwiftStrings

SwiftStrings部分主要介绍Swift字符串与字符。Swift的String和Character类型提供了一种快速的兼容Unicode的方式处理文本,字符串的每个字符都是Unicode字符,支持访问Unicode的不同表示形式。

import Foundation

// 每个字符串都是由编码无关的Unicode字符组成

// 创建一个空字符串
var emptyString = ""
var anotherEmptyString = String()

// 通过isEmpty属性来判断字符串是否为空
if emptyString.isEmpty {
    print("Nothing to see here")
}

// 通过for-in循环遍历字符串的characters属性来获取每个字符的值
for character in "Dog!".characters {
    print(character)
}

// 字符串可以通过character字符数组初始化
let catCharacters:[Character] = ["C", "a", "t"]
let catString = String(catCharacters)
print(catString)

// 连接字符串
let string1 = "Hello "
let string2 = "there"
var welcome = string1 + string2
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
print(welcome)

// \u{}表示Unicode字符,注意大括号里面的数值是十六进制
let dollarSign = "\u{24}"
let blackHeart = "\u{2665}"
let sparklingHeart = "\u{1F496}"
print(dollarSign, blackHeart, sparklingHeart)

// Swift字符Character是采用可扩展字符集,即有的字符是由多个Unicode字符组合而成
let exampleCharacter1 = "\u{1112}\u{1161}\u{11AB}"
let exampleCharacter2 = "\u{D55C}"
print(exampleCharacter1,exampleCharacter2)

// 字符串的characters.count方法计算的是字符串有多少字符组成
let unusualMenagerie = "Koala\u{1F1FA}\u{1F1F8}"
print(unusualMenagerie)
print(unusualMenagerie.characters.count)
var word = "cafe"
print("the number of characters in \(word) is \(word.characters.count)")
word += "\u{301}"
print("the number of characters in \(word) is \(word.characters.count)")

// 字符串索引,String.Index,不支持整数做索引
// predecessor()取前一个索引,successor()取后一个索引
// advancedBy()获取索引
// 越界会引发运行时候错误
let greeting = "Guten Tag!"
print(greeting[greeting.startIndex])
print(greeting[greeting.endIndex.predecessor()])
print(greeting[greeting.startIndex.successor()])
let index = greeting.startIndex.advancedBy(7)
print(greeting[index])
print(word[greeting.startIndex])
print(greeting[index.advancedBy(1)])
print(greeting[index.advancedBy(2, limit: greeting.endIndex)])

// 使用characters属性的indices属性会创建一个包含所有索引的范围
for index in greeting.characters.indices {
    print("\(greeting[index])", terminator: " ")
}

// 调用insert()插入元素
// 调用insertContentsOf()插入字符串
welcome.insert("!", atIndex: welcome.endIndex)
print(welcome)
welcome.insertContentsOf("here".characters, at: welcome.endIndex.predecessor())
print(welcome)

// removeAtIndex()删除索引指定的元素
// removeRange()删除索引范围元素
welcome.removeAtIndex(welcome.endIndex.predecessor())
print(welcome)
welcome.removeRange(welcome.endIndex.advancedBy(-4)..\<welcome.endIndex)
print(welcome)

// 调用hasPrefix()判断是否包含指定前缀
// 调用hasSuffix()判断是否包含指定后缀
let prefixAndSuffix = ["abc123", "absfeh23", "23"]
var prefix = 0
var suffix = 0
for i in prefixAndSuffix {
    if i.hasPrefix("ab") {
        prefix++
    }
    if i.hasSuffix("23") {
        suffix++
    }
}
print(prefix, suffix)

//Unicode编码形式,UTF-8(编码字符串为8位),UTF-16,UTF-32
let dogString = "Dog!????"
for codeUnit in dogString.utf8 {
    print("\(codeUnit)", terminator: " ")
}
print("")
for codeUnit in dogString.unicodeScalars {
    print("\(codeUnit.value)", terminator: " ")
}
print("")
for codeUnit in dogString.unicodeScalars {
    print("\(codeUnit)", terminator: " ")
}
print("")
print(dogString.utf8.count)
print(dogString.utf16.count)
print(dogString.unicodeScalars.count)

// 字符串比较时需注意
// 两个字符,即便构成它们的Unicode标量不同,只要它们拥有同样的语言意义和外观,就认为它们相等
let s1 = "caf\u{E9}"
let s2 = "caf\u{65}\u{301}"
print(s1, s2)
if s1 == s2 {
    print("equal string")
}

SwiftCollectionTypes

SwiftCollection部分主要介绍Swift中的三种集合类型Array、Set、Dictionary,Swift中集合类型封装了很多属性和方法,语法特性都与C语言有较大的区别。

Array

import Foundation

// Swift提供Array、Set、Dictionary三种集合类型

// 创建一个空数组
// 如果创建时数组类型已知,可以直接用[]定义一个空数组
var someInts = [Int]()
someInts.append(3)
someInts = []

// 创建特定大小并且所有数据都被初始化
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)

// 通过两个数组相加创建一个数组
var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)
var sixDoubles = threeDoubles + anotherThreeDoubles
print(sixDoubles)

// 用字面值构造数组
var shoppingList1: [String] = ["Eggs", "Milk"]
var shoppingList2 = ["Eggs", "Milk"]

// count属性、isEmpty属性
// append()方法
if shoppingList1.isEmpty {
    print("Array is empty")
} else {
    print("not empty, count \(shoppingList1.count)")
}
shoppingList1.append("shoes")
shoppingList1 += ["water"]
print(shoppingList1)

// 允许使用整数索引
print(shoppingList1[0])
shoppingList1[0] = "six eggs"
shoppingList1[1...3] = ["Bananas", "Apples"]
print(shoppingList1)

// insert()和removeAtIndex()
shoppingList1.insert("Maple Syrup", atIndex: 0)
let mapleSyrup = shoppingList1.removeAtIndex(0)
print(mapleSyrup, shoppingList1)
let apples = shoppingList1.removeLast()
print(apples, shoppingList1)

// for-in遍历
for item in shoppingList1 {
    print(item)
}

// enumerate()方法遍历,返回每个数组元素索引值和元素值组成的元组
for (index, value) in shoppingList1.enumerate() {
    print("Item \(index+1): \(value)")
}

Set

// 集合(Set)存储相同类型并且没有确定顺序的值。适用于元素顺序不重要或者希望元素只出现一次
// 集合只能存储可哈希化的类型,哈希值是Int类型的,相等的对象哈希值必须相同
// 自定义的类型作为集合的值或者字典的Key,自定义的类型需符合Hashable协议,提供一个类型位Int的可读属性hashValue
// 因为Hashable 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
[Swift]LeetCode146.LRU缓存机制|LRUCache发布时间:2022-07-13
下一篇:
WWDC2018:Swift更新了什么?发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap