打开Array中包含的类型

时间:2017-09-21 11:26:29

标签: ios swift swift4

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

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确实有用。

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相同的操作吗?

1 个答案:

答案 0 :(得分:0)

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

按预期