gpt4 book ai didi

swift - Switch Case Cast 模式匹配

转载 作者:行者123 更新时间:2023-11-28 05:48:29 25 4
gpt4 key购买 nike

let number: Any = 10

switch number {
case 10 as Int:
print ("10")
default:
break
}

我只是想知道编译器采取了哪些步骤来解析常量number 的值?编译器是否首先将 number 转换为 Int,然后将其与文字 10 进行比较?还是将 number10 进行比较,然后再进行转换?

最佳答案

您可以制作一些挂接到调用的各种函数中的检测数据类型,并打印有关它们的详细信息。这将帮助您深入了解事物的顺序:

struct InstrumentedInt: ExpressibleByIntegerLiteral, Equatable {
let value: Int

init(integerLiteral: Int) {
print("Initializing InstrumentedInt from \(integerLiteral)")
self.value = integerLiteral
}

static func == (lhs: InstrumentedInt, rhs: InstrumentedInt) -> Bool {
print("checking \(lhs) == \(rhs)")
return lhs.value == rhs.value
}
}

struct InstrumentedDouble: ExpressibleByFloatLiteral, Equatable {
let value: Double

init(integerLiteral: Int) {
print("Initializing InstrumentedInt from \(integerLiteral)")
self.value = Double(integerLiteral)
}

init(floatLiteral: Double) {
print("Initializing InstrumentedInt from \(floatLiteral)")
self.value = floatLiteral
}

static func == (lhs: InstrumentedDouble, rhs: InstrumentedDouble) -> Bool {
print("checking \(lhs) == \(rhs)")
return lhs.value == rhs.value
}
}

func instrumentedValueProducer(value: Any) -> Any {
print("Producing value \(value)")
return value
}

let instrumentedInt: InstrumentedInt = 10
let instrumentedDouble: InstrumentedDouble = 20.0

switch instrumentedValueProducer(value: instrumentedDouble) {
case 10 as InstrumentedInt: print("10 as InstrumentedInt")
case 20.0 as InstrumentedDouble: print("20 as InstrumnetedDouble")
default: print("default")
}

Initializing InstrumentedInt from 10

Initializing InstrumentedInt from 20.0

Producing value InstrumentedDouble(value: 20.0)

Initializing InstrumentedInt from 20.0

checking InstrumentedDouble(value: 20.0) == InstrumentedDouble(value: 20.0)

20 as InstrumentedDouble

令人惊讶的是,即使 20 是第二种情况,编译器也不会调用初始化器 InstrumentedInt.init(integerLiteral: 10) 来进行比较。我想优化能够很聪明,并以某种方式创建一个完全跳过值(value)生成的查找表。

关于swift - Switch Case Cast 模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53795599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com