什么时候使用typealias?

时间:2017-11-21 22:24:54

标签: swift type-alias

到目前为止,我知道typealias是现有类型的命名别名。通过使用typealias,我可以做类似的事情:

typealias MyString = String
var str: MyString?

typealias Strings = [String]
var strs: Strings?

导致将str变量声明为String,将strs声明为字符串数组。

即使是自定义类型:

class MyClass {}
typealias MyClsType = MyClass
var myClass: MyClsType

然而,它似乎有点 unuseful ;从逻辑上讲,将例如var str: MyString?声明为String而不是var str: String?的目的是什么?更重要的是,var str: String更具表现力。

2 个答案:

答案 0 :(得分:18)

实际上,毫无疑问为-let创建了一个类型字符串:字符串:typealias MyString = String不会有用,(我还假设为字典声明了一个类型的字符串特定键/值类型:typealias CustomDict = Dictionary<String, Int>可能对您没用。

但是,当使用 compound types 时,您肯定会注意到类型别名的好处。

示例:

考虑您正在实现管理器,该管理器在其函数中重复使用具有许多参数的闭包:

class MyManager {
    //...

    func foo(success: (_ data: Data, _ message: String, _ status: Int, _ isEnabled: Bool) -> (), failure: (_ error: Error, _ message: String, _ workaround: AnyObject) -> ()) {
        if isSuccess {
            success(..., ..., ..., ...)
        } else {
            failure(..., ..., ...)
        }
    }

    func bar(success: (_ data: Data, _ message: String, _ status: Int, _ isEnabled: Bool) -> (), failure: (_ error: Error, _ message: String, _ workaround: AnyObject) -> ()) {
        if isSuccess {
            success(..., ..., ..., ...)
        } else {
            failure(..., ..., ...)
        }
    }

    // ...
}

正如您所看到的,方法签名看起来真的乏味!这两个方法都采用successfailure个参数,每个参数都是带参数的闭包;此外,为了实现类似的功能,保持复制粘贴参数并不合乎逻辑。

为这种情况实施typealias是非常恰当的:

class MyManager {
    //...

    typealias Success = (_ data: Data, _ message: String, _ status: Int, _ isEnabled: Bool) -> ()
    typealias Failure = (_ error: Error, _ message: String, _ workaround: AnyObject) -> ()

    func foo(success: Success, failure: Failure) {
        if isSuccess {
            success(..., ..., ..., ...)
        } else {
            failure(..., ..., ...)
        }
    }

    func bar(success: Success, failure: Failure) {
        if isSuccess {
            success(..., ..., ..., ...)
        } else {
            failure(..., ..., ...)
        }
    }

    // ...
}

因此它会更具表现力和可读性。


此外 ,您可能需要查看我发布的medium story

答案 1 :(得分:0)

为我使用typealias的常用方法是使用闭包:

typealias VoidClosure = () -> Void

func updateFrom(completion: @escaping VoidClosure) { }