官术网_书友最值得收藏!

Generic functions

In Swift, the simplest form of generics would be the generics in functions. You can use generics very simply, with angled brackets, as follows:

func concat<T>(a: T, b: T) -> [T] {
return [a,b]
}

The concat method knows nothing about the types that you are passing in, but generics gives us many guarantees over using Any:

  • a and b should be of the same type
  • The return type is an array of elements that have the same type as a and b
  • The type is inferred from the context so you don't have to type it in when you code

You can also leverage protocol conformance in your generic functions, as follows:

protocol Runnable {
func run()
}

func run<T>(runnable: T) where T: Runnable {
runnable.run()
}

In this case, the method that is run can only be called with an object that is Runnable.

主站蜘蛛池模板: 景宁| 即墨市| 丰原市| 遵化市| 东阿县| 康定县| 溧水县| 民丰县| 怀来县| 即墨市| 太仓市| 万全县| 社旗县| 万山特区| 五河县| 霞浦县| 东明县| 忻城县| 布拖县| 志丹县| 奉新县| 兴海县| 老河口市| 桦南县| 奎屯市| 遵义县| 志丹县| 永济市| 额尔古纳市| 新乐市| 淄博市| 景德镇市| 南乐县| 铁力市| 沂南县| 林州市| 洛阳市| 玛曲县| 双江| 泸溪县| 旌德县|