簡體   English   中英

Swift-使func類型顯式(在協議中)

[英]Swift - Make func type explicit (in protocol)

假設我們有一個帶有typealias的協議,如下所示:

// common closure types
typealias Action = () -> Void
typealias Consumer<T> = (T) -> Void

// here starts the fun
typealias AsyncAction = (Action?) -> Void
typealias AsyncGetter<T> = (Consumer<T>?) -> Void
typealias AsyncSetter<T> = (T, Action?) -> Void

// make compiler and you happy
typealias Foo = Void
typealias Bar = Void

protocol FooBarDatabaseAccess {
    func doSomething()
    func doSomethingAsync(completion: Action?)//: AsyncAction
    func getFooAsync(completion: Consumer<Foo>?)//: AsyncGetter<Foo>
    func getBarAsync(completion: Consumer<Bar>?)//: AsyncGetter<Bar>
    func setBarAsync(value: Bar, completion: Action?)//: AsyncSetter<Bar>
}


我想指定類似於let / var聲明的函數類型,並在其后加上可分配類型:

/* -- let/var -- */

// implicitly typed as String, determined from initial assignment
let implicitString = ""

// explicitly typed as String, though initialisation is omitted here
let explicitString: String


/* -- func -- */

// implicitly typed as () -> Void, determined from argument/return type(s)
func implicitAction()

// explicitly typed as Action, compiler should complain if it does not conform to the type (alias)
???


我該如何實現?

可能的解決方法是將其轉換為屬性聲明,但這令人困惑:

var explicitAction: Action = { get }

由於Action是類型typealias而不是類型,因此swift無法區分它們。

文檔中所述:

聲明類型別名后,可以使用別名代替程序中各處的現有類型。 現有類型可以是命名類型或復合類型。 類型別名不會創建新類型。 它們僅允許名稱引用現有類型。

編輯:我不好,我想你想區分() -> VoidAction 據我所知,使用閉包是快速完成此操作的唯一方法。

typealias Foo = (Int) -> Void

protocol FooBar {
  var foo: Foo { get }
}

class FooBarBaz: FooBar {
  var foo: Foo = { intValue in
    // ...
  }
}

編輯2:其他信息:

根據函數聲明語法,聲明函數唯一方法是顯式提供一個parameter-clause ,該parameter-clause要求在括號之間列出所有參數:

函數聲明→函數頭函數名泛型子句opt 函數簽名泛型子句opt函數體opt

函數簽名→ 參數子句拋出opt函數結果opt

參數子句→()| (參數列表)

因此,顯然,如果不使用閉包,就不可能將類型聲明為簽名的函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM