gpt4 book ai didi

ios - 打开数组中包含的类型

转载 作者:行者123 更新时间:2023-11-30 12:08:43 25 4
gpt4 key购买 nike

我想从作为参数传递给函数的数组中提取类型,以使类型参数可选。

init(type: ContentType? = nil, style: LayoutStyle, content: [ContentProtocol]) {
self.type = type ?? {
switch content {
case is [Ad]: return .ads
case is [User]: return .users
case is [List]: return .list
default: fatalError("Can't assume.")
}
}()
}

AdUserList 均符合 ContentProtocol

这些 switch 语句会导致错误,“可选类型 '[Ad/User/List]' 不能用作 bool 值;改为测试 '!= nil'” 这不是我想要的想做。

但是这个初始化确实有效。

init(type: ContentType? = nil, style: LayoutStyle, fetcher: ContentFetcher) {
self.type = type ?? {
switch fetcher {
case is AdFetcher: return .ads
case is UserFetcher: return .users
case is ListFetcher: return .list
default: fatalError("Can't assume.")
}
}()
}

ContentFetcher是另一个协议(protocol),switch语句中的所有类型都遵循这个协议(protocol)。

我可以用第一个 init 实现与最后一个 init 相同的效果吗?

最佳答案

protocol P{}
struct A: P{}
struct B: P{}
struct C: P{}

let a = [A(), A()]
let b = [B(), B()]
let c = [C(), C()]

func foo(arr: [P]) {
if let a = arr as? [A] {
print(1, "A", a, type(of: a))
} else if let b = arr as? [B] {
print(1, "B", b, type(of: b))
} else {
print("not A nor B")
}

switch arr {
case let a where a is [A]:
print(2, "A", a, type(of: a))
case let b where b is [B]:
print(2, "B", b, type(of: b))
default:
print("not A nor B")
}
print()
}

foo(arr: a)
foo(arr: b)
foo(arr: c)

打印

1 A [__lldb_expr_245.A(), __lldb_expr_245.A()] Array<A>
2 A [__lldb_expr_245.A(), __lldb_expr_245.A()] Array<P>

1 B [__lldb_expr_245.B(), __lldb_expr_245.B()] Array<B>
2 B [__lldb_expr_245.B(), __lldb_expr_245.B()] Array<P>

not A nor B
not A nor B

如果输入数组是

let d:[P] = [A(), B()]

打印

not A nor B
not A nor B

正如预期

关于ios - 打开数组中包含的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46342727/

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