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

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.

主站蜘蛛池模板: 沅陵县| 庆云县| 江永县| 波密县| 甘肃省| 娄底市| 宜丰县| 休宁县| 涞水县| 娄烦县| 阿勒泰市| 贵阳市| 临沧市| 项城市| 崇文区| 遵义市| 汪清县| 沛县| 湘西| 泰安市| 基隆市| 桃江县| 河间市| 白水县| 昌乐县| 夏河县| 荣昌县| 邮箱| 广水市| 平谷区| 乡宁县| 佛山市| 平度市| 新邵县| 贞丰县| 二连浩特市| 二连浩特市| 邹平县| 新丰县| 方城县| 揭西县|