Swift基础

本文是个比较简单的学习笔记,更详细的内容见 Swift官方文档

1、相等性比较

Swift标准库用 < 和 == 运算符定义了 >、>=、<=,所以实现 Comparable 的 < 运算符就会自动得到这些运算符的实现,实际上 Comparable 继承自 Equatable,所以 == 运算也是必须实现的,以下是示例代码

struct Point: Comparable, CustomStringConvertible {let x: Intlet y: Intvar description: String {return "Point(\(x), \(y))"}static func ==(lhs: Point, rhs: Point) -> Bool {return lhs.x == rhs.x && lhs.y == rhs.y}static func <(lhs: Point, rhs: Point) -> Bool {return lhs.x < rhs.x && lhs.y < rhs.y}static func + (left: Point, right: Point) -> Point {return Point(x: left.x + right.x, y: left.y + right.y)}
}let a = Point(x: 3, y: 4)
let b = Point(x: 3, y: 4)
let abEqual = (a == b)
a != blet c = Point(x: 2, y: 6)
let d = Point(x: 3, y: 7)
c == d
c < d
c <= d
c > d
c >= dc + dclass Person: Equatable {let name: Stringlet age: Intweak var brother: Person?init(name: String, age: Int) {self.name = nameself.age = age}static func ==(lhs: Person, rhs: Person) -> Bool {return lhs.name == rhs.name}
}let p1 = Person(name: "JJF", age: 33)
let p2 = Person(name: "JZF", age: 36)
var people = [p1, p2]
if let p1Index = people.firstIndex(where: { $0 == p2 }) {print(p1Index)
}//自定义运算符
infix operator +++func +++(lhs: Person, rhs: Person) {lhs.brother = rhsrhs.brother = lhs
}
p1 +++ p2
p1.brother?.name
p2.brother?.name

2、日期和时间

import Foundationlet date = Date.nowlet dateFormatter = DateFormatter()
//dateFormatter.locale = Locale(identifier: "zh_CN")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"// typealias TimeInterval = Double
// A number of seconds.
// TimeInterval 是 Double 类型,单位是秒,可精确到微秒
//时间戳,1970到现在的毫秒数
let timestamp = Int(date.timeIntervalSince1970 * 1000)
print("timestamp = \(timestamp)")//取当前时间的年/月/日/时/分/秒/毫秒
var calendar = Calendar.current
let year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
let second = calendar.component(.second, from: date)
let milliSecond = calendar.component(.nanosecond, from: date) / 1000_000
print("\(year)-\(String(format: "%02D", month))-\(String(format: "%02D", day)) \(String(format: "%02D", hour)):\(String(format: "%02D", minute)):\(String(format: "%02D", second)).\(String(format: "%03D", milliSecond))")//使用 DateFormatter 格式化时间
print("\(dateFormatter.string(from: date))")let str = "Hello World!"
let start = str.index(str.startIndex, offsetBy: 6)
let end = str.index(str.startIndex, offsetBy: 11)
let substr = String(str[start..<end])
print(substr)

3、处理异常 

enum Token {case number(Int)case plus
}class Lexer {enum Error: Swift.Error {case invalidCharacter(Character)}let input: Stringvar position: String.Indexinit(input: String) {self.input = inputself.position = self.input.startIndex}func peek() -> Character? {guard position < input.endIndex else {return nil}return input[position]}func advance() {//断言只在调试模式下生效,发布模式下可使用 precondition(_:_:) 替代assert(position < input.endIndex, "Cannot advance past endIndex!")position = input.index(after: position)}func lex() throws -> [Token] {var tokens = [Token]()while let nextCharacter = peek() {switch nextCharacter {case "0"..."9":tokens.append(.number(getNumber()))case "+":tokens.append(.plus)advance()case " ":advance()default:throw Lexer.Error.invalidCharacter(nextCharacter)}}return tokens}func getNumber() -> Int {var value = 0while let nextCharacter = peek() {switch nextCharacter {case "0"..."9":let digitValue = Int(String(nextCharacter))!value = 10 * value + digitValueadvance()default:return value}}return value}
}class Parser {enum Error: Swift.Error {case unexpectedEndOfInputcase invalidToken(Token)}let tokens: [Token]var position = 0init(tokens: [Token]) {self.tokens = tokens}func nextToken() -> Token? {guard position < tokens.count else {return nil}let token = tokens[position]position += 1return token}func getNumber() throws -> Int {guard let token = nextToken() else {throw Parser.Error.unexpectedEndOfInput}switch token {case .number(let value):return valuecase .plus:throw Parser.Error.invalidToken(token)}}func parse() throws -> Int {var value = try getNumber()while let token = nextToken() {switch token {case .plus:let nextNumber = try getNumber()value += nextNumbercase .number:throw Parser.Error.invalidToken(token)}}return value}
}func evaluate(_ input: String) {print("Evaluating: \(input)")let lexer = Lexer(input: input)
//    let tokens = try! lexer.lex()//强制执行可能抛出错误的方法,发生错误时触发陷阱
//    guard let tokens = try? lexer.lex() else {
//        print("Lexing failed, but I don't know why")
//        return
//    }do {let tokens =  try lexer.lex()print("Lexer ouput: \(tokens)")let parser = Parser(tokens: tokens)let value = try parser.parse()print(value)} catch Lexer.Error.invalidCharacter(let character) {print("Input contained an invalid character: \(character)")} catch Parser.Error.unexpectedEndOfInput {print("Unexpected end of input during parsing")} catch Parser.Error.invalidToken(let token) {print("Invalid token during parsing: \(token)")} catch {print("An error occurred: \(error)")}
}
evaluate("10 + 3 + 5 +")

4、扩展

(1)扩展类/结构体

typealias Velocity = Doubleextension Velocity {var kph: Velocity { return self * 1.60934 }var mph: Velocity { return self }
}protocol Vehicle {var topSpeed: Velocity { get }var numberOfDoors: Int { get }var hasFlatbed: Bool { get }
}struct Car {let make: Stringlet model: Stringlet year: Intlet color: Stringlet nickname: Stringvar gasLevel: Double {willSet {precondition(newValue <= 1.0 && newValue >= 0.0, "New value must between 0 and 1.")}}
}//利用拓展使 Car 实现协议
extension Car: Vehicle {var topSpeed: Velocity { return 180 }var numberOfDoors: Int { return 4 }var hasFlatbed: Bool { return false }
}//利用拓展给 Car 增加初始化方法,这样会保留默认的成员初始化方法
extension Car {init(make: String, model: String, year: Int) {self.init(make: make, model: model, year: year, color: "Black", nickname: "N/A", gasLevel: 1.0)}
}var c = Car(make: "Ford", model: "Fusion", year: 2013)extension Car {enum Kind {case coupe, sedan}var kind: Kind {if numberOfDoors == 2 {return .coupe} else {return .sedan}}
}
c.kindextension Car {mutating func  emptyGas(by amount: Double) {precondition(amount <= 1 && amount > 0, "Amount to remove must be between 0 and 1.")gasLevel -= amount}mutating func fillGas() {gasLevel = 1.0}
}
c.emptyGas(by: 0.3)
c.gasLevel
c.fillGas()
c.gasLevel

(2)扩展协议

protocol Exercise: CustomStringConvertible {var name: String { get }var caloriesBurned: Double { get } //消耗的卡路里var minutes: Double { get }//锻炼的时长
}extension Exercise {var description: String {return "Exercise(\(name), burned \(caloriesBurned) calories in \(minutes) minutes)"}
}extension Exercise {var title: String {return "\(name) - \(minutes) minutes"}
}struct EllipticalWorkout: Exercise {let name: String = "Elliptical Workout"let title: String = "Workout using the Go Fast Elliptical Trainer 3000"let caloriesBurned: Doublelet minutes: Double
}struct TreadmillWorkout: Exercise {let name: String = "Treadmill Workout"let caloriesBurned: Doublelet minutes: Doublelet laps: Double //跑步的圈数
}
extension TreadmillWorkout {var description: String {return "TreadmillWorkout(\(caloriesBurned) calories and \(laps) laps in \(minutes) minutes)"}
}let ellipticalWorkout = EllipticalWorkout(caloriesBurned: 335, minutes: 30)
let runningWorkout = TreadmillWorkout(caloriesBurned: 350, minutes: 25, laps: 10.5)
//使用范型定义函数:计算每分钟消耗的卡路里
func caloriesBurnedPerMinute<E: Exercise>(for exercise: E) -> Double {return exercise.caloriesBurned / exercise.minutes
}
print(caloriesBurnedPerMinute(for: ellipticalWorkout))
print(caloriesBurnedPerMinute(for: runningWorkout))//拓展协议
extension Exercise {//所有实现该协议的类型都可以使用通过拓展为该协议添加的属性和方法var caloriesBurnedPerMinute: Double {return caloriesBurned / minutes}
}print(ellipticalWorkout.caloriesBurnedPerMinute)
print(runningWorkout.caloriesBurnedPerMinute)
print(ellipticalWorkout)
print(runningWorkout)//带 where 子句的协议拓展
extension Sequence where Iterator.Element == Exercise {func totalCaloriesBurned() -> Double {var total: Double = 0for exercise in self {total += exercise.caloriesBurned}return total}
}let mondayWorkout: [Exercise] = [ellipticalWorkout, runningWorkout]
print(mondayWorkout.totalCaloriesBurned())for exercise in mondayWorkout {print(exercise.title)
}
print(ellipticalWorkout.title)

5、范型

struct StackIterator<T>: IteratorProtocol {
//    typealias Element = Tvar stack: Stack<T>mutating func next() -> T? {return stack.pop()}
}// Sequence 是实现 for-in 循环在内部使用的协议
struct Stack<E>: Sequence {var items = [E]()// 使用 where 子句约束 Sequence 的元素类型mutating func pushAll<S: Sequence>(_ sequence: S) where S.Iterator.Element == E {for item in sequence {self.push(item)}}mutating func push(_ newItem: E) {items.append(newItem)}mutating func pop() -> E? {guard !items.isEmpty else {return nil}return items.removeLast()}func map<U>(_ f: (E) -> U) -> Stack<U> {var mappedItems = [U]()for item in items {mappedItems.append(f(item))}return Stack<U>(items: mappedItems)}func makeIterator() -> StackIterator<E> {return StackIterator(stack: self)}
}var intStack = Stack<Int>()
intStack.push(1)
intStack.push(2)
var doubledStack = intStack.map { 2 * $0 }print(intStack.pop())
print(intStack.pop())
print(intStack.pop())
print(doubledStack.pop())
print(doubledStack.pop())func myMap<T, U>(_ items: [T], _ f: (T) -> U) -> [U] {var result = [U]()for item in items {result.append(f(item))}return result
}
let strings = ["one", "two", "three"]
//let stringLengths = myMap(strings, {(str: String) -> Int in
//    return str.count
//})
let stringLengths = myMap(strings) { $0.count }
print(stringLengths)//类型约束
func checkIfEqual<T: Equatable>(_ first: T, _ second: T) -> Bool {return first == second
}
print(checkIfEqual(1, 1))
print(checkIfEqual("a string", "a string"))
print(checkIfEqual("a string", "a different string"))//每个占位类型都可以有一个类型约束
func checkIfDescriptionsMatch<T: CustomStringConvertible, U: CustomStringConvertible>(_ first: T, _ second: U) -> Bool {return first.description == second.description
}print(checkIfDescriptionsMatch(Int(1), UInt(1)))
print(checkIfDescriptionsMatch(1, 1.0))
print(checkIfDescriptionsMatch(Float(1.0), Double(1.0)))var myStack = Stack<Int>()
myStack.push(10)
myStack.push(20)
myStack.push(30)
var myStackIterator = StackIterator(stack: myStack)
while let value = myStackIterator.next() {print("got \(value)")
}for value in myStack {print("for-in loop: got \(value)")
}
myStack.pushAll([1, 2, 3])
for value in myStack {print("after pushing: got \(value)")
}
var myOtherStack = Stack<Int>()
myOtherStack.pushAll([1, 2, 3])
myStack.pushAll(myOtherStack)
for value in myStack {print("after pushing item onto stack, got \(value)")
}

6、协议

protocol TabularDataSource {var numberOfRows: Int { get }var numberOfColumns: Int { get }func label(forColumn column: Int) -> Stringfunc itemFor(row: Int, column: Int) -> String
}protocol PrintableTabularDataSource: TabularDataSource, CustomStringConvertible {//
}//组合协议,让 printTable 的参数符合 CustomStringConvertible 协议
func printTable(_ dataSource: TabularDataSource & CustomStringConvertible) {print(dataSource)var firstRow = "|"var columnWidths = [Int]()for i in 0..<dataSource.numberOfColumns {let columnLabel = dataSource.label(forColumn: i)let columnHeader = " \(columnLabel) |"firstRow += columnHeadercolumnWidths.append(columnLabel.count)}print(firstRow)for i in 0..<dataSource.numberOfRows {var out = "|"for j in 0..<dataSource.numberOfColumns {let item = dataSource.itemFor(row: i, column: j)let paddingNeeded = columnWidths[j] - item.countlet padding = repeatElement(" ", count: paddingNeeded).joined(separator: "")out += " \(padding)\(item) |"}print(out)}
}struct Person {let name: Stringlet age: Intlet yearsOfExperience: Int
}struct Department: TabularDataSource, CustomStringConvertible {let name: Stringvar people = [Person]()var description: String {return "Department (\(name))"}init(name: String) {self.name = name}mutating func add(_ person: Person) {people.append(person)}var numberOfRows: Int {return people.count}var numberOfColumns: Int {return 3}func label(forColumn column: Int) -> String {switch column {case 0: return "Employee Name"case 1: return "Age"case 2: return "Years of Experience"default: fatalError("Invalid column!")}}func itemFor(row: Int, column: Int) -> String {let person = people[row]switch column {case 0: return person.namecase 1: return String(person.age)case 2: return String(person.yearsOfExperience)default: fatalError("Invalid column!")}}
}var department = Department(name: "Engineering")
department.add(Person(name: "Joe", age: 30, yearsOfExperience: 6))
department.add(Person(name: "Karen", age: 40, yearsOfExperience: 18))
department.add(Person(name: "Fred", age: 50, yearsOfExperience: 20))printTable(department)

7、字符串

import Cocoaextension String {/// 截取字符串/// - Parameter start: 起始索引(包含)/// - Parameter end: 结束索引(不包含)func substring(start: Int, end: Int) -> String {let firstIndex = index(startIndex, offsetBy: start)let lastIndex = index(startIndex, offsetBy: end)return String(self[firstIndex..<lastIndex])}/// 16进制字符串(可以有空格)转换成二进制数据func toData() -> Data {let hex = self.replacingOccurrences(of: " ", with: "")var arr = Array<UInt8>()for i in 0..<hex.count where i % 2 == 0 {let byteStr = hex.substring(start: i, end: i + 2)//        print("byteStr = \(byteStr)")arr.append(UInt8(byteStr, radix: 16) ?? 0)}return Data(arr)}
}extension Data {/// 按照 ASCII 转换成字符串func toAscii() -> String {return subdata2ascii(start: 0, end: self.count)}/// 转换成16进制字符串/// - Parameter withSpace: 可选参数,默认true,输出的字符串是否每两个字节之间放一个空格func toHex(withSpace: Bool = true) -> String {return subdata2hex(start: 0, end: self.count, withSpace: withSpace)}/// 将指定范围的数据转换成ASCII字符串/// - Parameter start: 起始索引(包含)/// - Parameter end: 结束索引(不包含)func subdata2ascii(start: Int, end: Int) -> String {if let str = String(data: self[start..<end], encoding: .ascii) {return str}return ""}/// 将指定范围的数据转换成16进制字符串/// - Parameter start: 起始索引(包含)/// - Parameter end: 结束索引(不包含)/// - Parameter withSpace: 可选参数,默认true,输出的字符串是否每两个字节之间放一个空格func subdata2hex(start: Int, end: Int, withSpace: Bool = true) -> String {let arr = Array<UInt8>(self[start..<end])let hex = arr.map({ byte -> String inreturn String(format: "%02X", byte)}).joined(separator: withSpace ? " " : "")return hex}
}func test() {let hexString = "5A 58 48 0C 83 0E 47 07 22 2B 42 41 30 34 56 30 35"let data = hexString.toData()print("head = \(data.subdata2ascii(start: 0, end: 3))")print("mac = \(data.subdata2hex(start: 3, end: 9))")print("DeviceType = \(data.subdata2ascii(start: 9, end: 14))")print("version = \(data.subdata2ascii(start: 14, end: data.count))")print(data.toHex(withSpace: true))
}test()let apples = 3
let oranges = 5
//只要与结束引号(""")的缩进匹配,就会删除每一行开始处的缩进
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."""
print(quotation)

8、类和结构体

/** struct 类似 Kotlin 的 data class,等价写法是:data class Person(var firstName: String = "Matt", var lastName: String = "Mathias")*/
struct Person {var firstName = "Matt"var lastName = "Mathias"
}var p = Person(firstName: "Jia", lastName: "Jiefei")
print(p)//如果属性没有提供默认值,结构体会根据属性生成默认的成员初始化方法,并且直接打印结构体可以看到所有存储属性的值
struct Device {var name: Stringvar address: String// text 是计算属性,打印时不会输出var text: String {return "name=\(name), address=\(address)"}
}
print(Device(name: "Device", address: "11:22:33:44:55:66"))//而类就没有默认成员初始化方法了,需要自己编写初始化方法,并且直接打印类实例,不会输出各存储属性的值
class BleDevice {var name: Stringvar address: Stringrequired init(name: String, address: String) {self.name = nameself.address = address}
}
print(BleDevice(name: "BleDevice", address: "AA:BB:CC:DD:EE:FF"))

9、值类型和引用类型

//类是引用类型
class GreekGod {var name: Stringinit(name: String) {self.name = name}
}let hecate = GreekGod(name: "Hecate")
let athena = GreekGod(name: "Athena")
let zeus = GreekGod(name: "Zeus")
let anotherHecate = hecate
anotherHecate.name = "AnotherHecate"
hecate.name //类是引用类型,改变 anotherHecate.name,hecate.name也会变//结构体是值类型
struct Pantheon {var chiefGod: GreekGod
}let pantheon = Pantheon(chiefGod: hecate)pantheon.chiefGod.name // AnotherHecate
let greekPantheon = pantheon
hecate.name = "Trivia"
greekPantheon.chiefGod.name // Trivialet gods = [athena, hecate, zeus]
let godsCopy = gods
gods.last?.name = "Jupiter"
godsCopy.last?.name // Jupiter//探究写时复制(copy on write, COW)
fileprivate class IntArrayBuffer {var storage: [Int]init() {storage = []}init(buffer: IntArrayBuffer) {storage = buffer.storage}
}struct IntArray {private var buffer: IntArrayBufferinit() {buffer = IntArrayBuffer()}func describe() {let str = buffer.storage.map { i inString(i)}.joined(separator: ", ")print("[\(str)]")
//        print(buffer.storage)}private mutating func copyIfNeeded() {//判断引用类型是否只有一个引用if !isKnownUniquelyReferenced(&buffer) {print("Making a copy of \(buffer.storage)")buffer = IntArrayBuffer(buffer: buffer)}}mutating func insert(_ value: Int, at index: Int) {copyIfNeeded()buffer.storage.insert(value, at: index)}mutating func append(_ value: Int) {copyIfNeeded()buffer.storage.append(value)}mutating func remove(at index: Int) {copyIfNeeded()buffer.storage.remove(at: index)}
}var integers = IntArray()
integers.append(1)
integers.append(2)
integers.append(4)
integers.describe()
var ints = integers
ints.insert(3, at: 2)
integers.describe()
ints.describe()

10、继承

虽然是讲继承,但代码中的注释也会涉及其他知识点!例子涉及3个.swift文件

Town.swift

struct Town {let region: Stringvar population: Int {didSet {print("The population has changed to \(population) from \(oldValue)")}}var numberOfStoplights: Int//自定义初始化方法,问号表示可失败的初始化方法init?(region: String, population: Int, stoplights: Int) {guard population > 0 else {return nil}self.region = regionself.population = populationnumberOfStoplights = stoplights}//委托初始化init?(population: Int, stoplights: Int) {self.init(region: "N/A", population: population, stoplights: stoplights)}enum Size {case smallcase mediumcase large}//计算属性var townSize: Size {get {print("town size")//每次调用都会打印switch self.population {case 0...10_000:return Size.smallcase 10_001...100_000:return Size.mediumdefault:return Size.large}}}//惰性存储属性,注意这里的等号以及结尾的圆括号lazy var name: String = {print("town name")//这里只会打印一次,即第一次访问该属性时return "XiShe"}()func printDescription() {print("Population: \(population), number of stoplights: \(numberOfStoplights), region: \(region)")}/* 如果结构体(确切的说,应该是值类型,结构体和枚举都是值类型)的一个实例方法需要修改结构体的属性,就必须使用 mutating 标记该方法 */mutating func changePopulation(by amount: Int) {population += amount}/* 对于值类型,类型方法使用static标记 */static func xxx() {}
}

Monster.swift

class Monster {// static 属性无法被子类覆盖static let isTerrifying = true// class 属性可被子类覆盖class var spookyNoise: String {return "Grrr"}var town: Town?var name: Stringvar victimPool: Int {get {return town?.population ?? 0}set {town?.population = newValue}}//子类必须得实现的初始化方法required init(town: Town?, monsterName: String) {self.town = townname = monsterName}func terrorizeTown() {if town != nil {print("\(name) is terrorizing a town!")} else {print("\(name) hasn't found a town to terrorize yet...")}}/* 对于类,类型方法使用class或者static标记,区别在于static标记的方法无法被子类重写,也可以使用final class代替static */static func makeSpookyNoise() {print("Brains...")}
}

Zombie.swift

class Zombie: Monster {override class var spookyNoise: String {return "Brains..."}var walkWithLimp: Bool//只将 set 属性设置为私有,get 属性为默认的 internalprivate(set) var isFallingApart: Bool//指定初始化方法init(limp: Bool, fallingApart: Bool, town: Town?, monsterName: String) {walkWithLimp = limpisFallingApart = fallingApart//如果有父类,子类的指定初始化方法必须调用父类的指定初始化方法super.init(town: town, monsterName: monsterName)}//便捷初始化方法,必须调用指定初始化方法或者其他便捷初始化方法,但最终都要调用指定初始化方法,以确保所有属性都进行了初始化convenience init(limp: Bool, fallingApart: Bool) {self.init(limp: limp, fallingApart: fallingApart, town: nil, monsterName: "Fred")if walkWithLimp {print("This zombie has a bad knee.")}}required init(town: Town?, monsterName: String) {walkWithLimp = falseisFallingApart = falsesuper.init(town: town, monsterName: monsterName)}//实例被清除出内存时会触发反初始化deinit {print("Zombie named \(name) is no longer with use.")}//final 禁止子类重写该方法final override func terrorizeTown() {if !isFallingApart {town?.changePopulation(by: -10)}super.terrorizeTown()}
}

 测试代码

var town = Town(region: "West", population: 10, stoplights: 6)
town?.printDescription()
for _ in 0..<3 {if let townSize = town?.townSize, let townName = town?.name {print(townSize)print(townName)}town?.changePopulation(by: 1_000_000)
}
//let genericMonster = Monster()
//genericMonster.town = town
//genericMonster.terrorizeTown()
var fredTheZombie: Zombie? = Zombie(limp: false, fallingApart: false, town: town, monsterName: "Fred")
//fredTheZombie.terrorizeTown()
//fredTheZombie.town?.printDescription()
//Monster.makeSpookyNoise()
print("Victim pool: \(fredTheZombie?.victimPool)")
fredTheZombie?.victimPool = 500
fredTheZombie = nil
print(Monster.spookyNoise)
print(Zombie.spookyNoise)

11、数组和字典

//初始化数组的3种方式,本人习惯上倾向使用第一种
//使用 var 就是可变数组,let就是不可变数组
var bucketList: Array<String> = []
var bucketList2:[String] = ["haha"]
var arr = [Int]()
arr.append(1)
arr.append(3)
arr.append(2)
//print("bucketList.count=\(bucketList.count) arr[0]=\(arr[0])")
//数组排序
let sortedArray = arr.sorted(by: {a, b ina < b
})
print(sortedArray)
//注:只有Array<String> 才有 joined 方法,如果元素类型不是 String,得先通过 map 方法转一次
let joinedString = arr.map { i inString(i)
}.joined(separator: ", ")
print("[\(joinedString)]")//字典也有多种初始化方式,这里只列出其中一种
//使用 var 就是可变字典,let就是不可变字典
var dict: Dictionary<String, Int> = [:]
dict["one"] = 1
dict["two"] = 2
dict["three"] = 3
//遍历字典
for (key, value) in dict {print("\(key) = \(value)")
}
dict.removeValue(forKey: "one")
dict["two"] = nil //将值设置为nil来删除键值对
print(dict)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/110959.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

spring boot MongoDB实战

项目搭建 <?xml version"1.0" encoding"UTF-8"?><project xmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation"http://maven.apache.org/POM/4.0.0 …

谈谈 Redis 如何来实现分布式锁

谈谈 Redis 如何来实现分布式锁 基于 setnx 可以实现&#xff0c;但是不是可重入的。 基于 Hash 数据类型 Lua脚本 可以实现可重入的分布式锁。 获取锁的 Lua 脚本&#xff1a; 释放锁的 Lua 脚本&#xff1a; 但是还是存在分布式问题&#xff0c;比如说&#xff0c;一个客…

李宏毅机器学习笔记-半监督学习

半监督学习&#xff0c;一般应用于少量带标签的数据&#xff08;数量R&#xff09;和大量未带标签数据的场景&#xff08;数量U&#xff09;&#xff0c;一般来说&#xff0c;U>>R。 半监督学习一般可以分为2种情况&#xff0c;一种是transductive learning&#xff0c;…

GO 语言的方法??

GO 中的方法是什么&#xff1f; 前面我们有分享到 GO 语言的函数&#xff0c;他是一等公民&#xff0c;那么 GO 语言中的方法和函数有什么区别呢&#xff1f; GO 语言中的方法实际上和函数是类似的&#xff0c;只不过在函数的基础上多了一个参数&#xff0c;这个参数在 GO 语…

O2O优惠券预测

O2O优惠券预测 赛题理解赛题类型解题思路 数据探索理论知识数据可视化分布 特征工程赛题特征工程思路 模型训练与验证 赛题理解 赛题类型 本赛题要求提交的结果是预测15 天内用券的概率&#xff0c;这是一个连续值&#xff0c;但是因为用券只有用与不用两种情况&#xff0c;而…

Redis入门到实战(四、原理篇)RESP协议

目录 2、Redis内存回收-过期key处理3、Redis内存回收-内存淘汰策略 Redis是一个CS架构的软件&#xff0c;通信一般分两步&#xff08;不包括pipeline和PubSub&#xff09;&#xff1a; 客户端&#xff08;client&#xff09;向服务端&#xff08;server&#xff09;发送一条命令…

数字秒表VHDL实验箱精度毫秒可回看,视频/代码

名称&#xff1a;数字秒表VHDL精度毫秒可回看 软件&#xff1a;Quartus 语言&#xff1a;VHDL 代码功能&#xff1a; 数字秒表的VHDL设计&#xff0c;可以显示秒和毫秒。可以启动、停止、复位。要求可以存储6组时间&#xff0c;可以回看存储的时间 本资源内含2个工程文件&am…

2023 年程序员必读的 27 本软件开发书籍

不断发展的软件开发领域需要不断学习和改进。现代开发实践要求软件工程师具备全面的知识&#xff0c;包括各个领域的理论见解和实践技术&#xff0c;从编程语言和数据库管理到质量保证、网页设计和 DevOps 实践。 这就是编程书籍可以提供帮助的地方。通过及时了解此类书籍并应…

[题] 求特殊自然数 #十进制转n进制

题目 NOI / 1.5编程基础之循环控制-25:求特殊自然数 题解 首先&#xff0c;不可能无限穷举 范围限定&#xff1a;七进制与九进制表示都是三位数 最大&#xff1a;888(9) 728(10) 最小&#xff1a;100(7) 49(10) 然后就是十进制转x进制的问题 n对xa取模&#xff0c;就是对应…

模拟退火算法求解TSP问题(python)

模拟退火算法求解TSP的步骤参考书籍《Matlab智能算法30个案例分析》。 问题描述 TSP问题描述在该书籍的第4章 算法流程 部分实现代码片段 坐标轴转换成两点之间直线距离长度的代码 coordinates np.array([(16.47, 96.10),(16.47, 94.44),(20.09, 92.54),(22.39, 93.37),(2…

如何给Github上的开源项目提交PR?

前言 对于一个热爱开源的程序员而言&#xff0c;学会给GitHub上的开源项目提交PR这是迈出开源的第一步。今天我们就来说说如何向GitHub的开源项目提交PR&#xff0c;当然你提交的PR可以是一个项目的需求迭代、也可以是一个Bug修复、再或者是一些内容文本翻译等等&#xff0c;并…

单片机点亮led管(01)

如何开始学习单片机 1&#xff1a;实践第一 2&#xff1a;补充必要的理论知识&#xff0c;缺什么补什么 3&#xff1a;做工程积累经验&#xff08;可以在网络上收集题目&#xff0c;也可以有自己的想法大胆的实验&#xff09; 单片机是什么&#xff1f; 单片机&#xff08…

ES 数据库

ES 数据库 通过 API 查询通过 JSON 查询 熟悉 es 的同学都知道 es 一般有两种查询方式 1&#xff0c;在 java 中构建查询对象&#xff0c;调用 es 提供的 api 做查询 2&#xff0c;使用 json 调用接口做查询 查询语句无非是将足够的信息丢给数据库&#xff0c;但是它却和 SQL …

5分钟内在Linux上安装.NET Core应用程序

作为开源的忠实粉丝&#xff0c;我喜欢 .NET Core 的跨平台特性。它开启了无限的可能性&#xff0c;从业余爱好项目、实验和概念验证&#xff0c;到在具有高安全性和可扩展性的经济高效基础设施上运行的大规模高负载生产应用程序。我通常从任何云平台提供商那里获得最简单、最便…

<C++> 模拟实现string

目录 前言 一、模拟实现string 1. 成员变量 2. 构造函数 2.1 构造函数 2.2 重载默认构造 2.3 合并 3. 析构函数 4. 拷贝构造函数 5. c_str 6. size 7. operator[ ] 7.1 普通版 7.2 const版本 8. 迭代器—iterator 8.1 普通版iterator 8.2 const版本iterator 9. 尾插 10. …

【微服务 SpringCloud】实用篇 · 服务拆分和远程调用

微服务&#xff08;2&#xff09; 文章目录 微服务&#xff08;2&#xff09;1. 服务拆分原则2. 服务拆分示例1.2.1 导入demo工程1.2.2 导入Sql语句 3. 实现远程调用案例1.3.1 案例需求&#xff1a;1.3.2 注册RestTemplate1.3.3 实现远程调用1.3.4 查看效果 4. 提供者与消费者 …

美创科技入选“内蒙古自治区第一届网络安全应急技术支撑单位”

近日&#xff0c;内蒙古自治区党委网信办、国家网络应急技术处理协调中心内蒙古分中心评选“内蒙古自治区网络安全应急技术支撑单位”结果公布。 经自治区各地区、各部门和单位推荐各单位自主申报&#xff0c;资料审查和专家评审等环节&#xff0c;美创科技成功入选“内蒙古自治…

Linux将磁盘空闲空间转移到其他目录下(home目录转移到root目录下)

目录 1、查看分区 2、备份home分区文件 &#xff08;重要&#xff09; 3、卸载/home 4、删除/home所在的lv 5、扩展/root所在的lv&#xff08;我这里还扩展了、dev/sr0&#xff09; 6、扩展/root文件系统。 7、重新创建home lv 创建时计算好剩余的磁盘容量&#xff0c;建…

数据预处理—滑动窗口采样数据

一个简单的例子&#xff1a; # data: 这是要应用滑动窗口采样的输入数据&#xff0c;通常是一个序列&#xff0c;例如列表或NumPy数组。 # window_size: 这是滑动窗口的大小&#xff0c;表示每个窗口中包含的元素数量。 # step_size: 这是滑动窗口移动的步长&#xff0c;表示每…

一个可以解决企业跨网文件交换难题的软件所具备的特性必须有哪些

在当今数字化办公的浪潮中&#xff0c;企业跨网文件交换成为了不可忽视的重要需求。无论是内部网络还是外部网络&#xff0c;都存在着各种跨网文件交换的场景&#xff0c;然而这一过程也面临着一系列的挑战。本文将深入探讨企业跨网文件交换的难题以及一款可以解决企业跨网文件…