【问题标题】:Swift closure conform to typealias including AnySwift 闭包符合类型别名,包括 Any
【发布时间】:2019-05-24 14:08:39
【问题描述】:

我有两个 typealias 声明

typealias QueryClosure = ((UInt?,UInt?)->([URLQueryItem])?)?
typealias SearchClosure = ((String?,UInt?)->([URLQueryItem])?)?

我为这些创建了闭包

var queryFunc: (QueryClosure)? = ( {a,b in
    return [URLQueryItem(name: "limit", value: "\(a ?? defaultPageSize)"), URLQueryItem(name: "offset", value: "\( (b ?? defaultPageIndex) * (a ?? defaultPageSize) )")]
})

var searchFunc: (SearchClosure)? = ( {query,b in
    return [URLQueryItem(name: "q", value: query), URLQueryItem(name: "page", value: "\(b ?? defaultPageIndex)")]
    }
)

现在我不想传递查询或搜索闭包,我想传递一般闭包。

所以我创建了一个新的类型别名

typealias VariableClosure = ((Any?, Any?)->([URLQueryItem]))?

但我无法转换为这种类型

let search : (VariableClosure) = ( {query,b in
    return [URLQueryItem(name: "q", value: query), URLQueryItem(name: "page", value: "\(b ?? defaultPageIndex)")]
    }
)

这给了我错误

Cannot convert value of type '(String?, _) -> [URLQueryItem]' to specified type 'VariableClosure' (aka 'Optional<(Optional<Any>, Optional<Any>) -> Array<URLQueryItem>>')

我如何创建一个符合 typealias 变量闭包的闭包(或更好的两个),或者以其他方式拥有一种我可以将我的闭包传递给的通用类型别名。

【问题讨论】:

  • 类型系统不应该像这样工作。您的意思是,任何人都可以将Anything 传递给名为searchVariableClosure,但实际上您只接受字符串和整数。
  • @Sweeper - 你有什么建议?我想要一个可以传递的通用闭包 - 有什么提示吗?

标签: swift


【解决方案1】:

由于URLQueryItem 接受String 并且您传递的query 变量属于Any 类型,因此在使用它之前,您必须首先将typecast query 转换为String

变量b 也是如此。使用前必须typecastInt

let search: VariableClosure = {query,b in
    if let query = query as? Int, let b = b as? Int {
        return [URLQueryItem(name: "limit", value: "\(query ?? 10)"), URLQueryItem(name: "offset", value: "\( (b ?? 10) * (query ?? 10) )")]
    } else if let query = query as? String, let b = b as? Int {
        return [URLQueryItem(name: "q", value: query), URLQueryItem(name: "page", value: "\(b ?? 1)")]
    }
    return nil
}

在上述情况下,如果您还期望其他类型的queryb,则必须手动处理它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多