【问题标题】:Switch on type contained in Array数组中包含的开关类型
【发布时间】:2017-09-23 15:58:18
【问题描述】:

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

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 语句会导致错误,"Optional type '[Ad/User/List]' cannot be used as a boolean; test for '!= nil' instead",这不是我想要做的。

然而,这个初始化确实有效。

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是另外一个协议,switch语句中的所有类型都符合这个。

第一个 init 可以达到与最后一个 init 相同的效果吗?

【问题讨论】:

  • 类似问题(可能的解决方法):stackoverflow.com/questions/24355513/…,Swift 错误报告:bugs.swift.org/browse/SR-5671
  • 我有一个关于你的代码的问题,我想知道如果它最初是 nil 并且你总是根据相同的另一个参数设置它的值,你为什么要在你的 init 中添加“type”参数init ("fetcher") ?
  • @Alex 我只是在滥用可选参数来拥有一个 init,如果我想强制它成为不同于 init 通常假设的东西,我可以使用显式类型调用它。此外,如果您不指定类型,它只会设置要从 content 参数假定的类型。

标签: ios swift swift4


【解决方案1】:
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

如预期的那样

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多