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

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.

主站蜘蛛池模板: 温宿县| 陈巴尔虎旗| 耿马| 屏东市| 江陵县| 阳原县| 天水市| 汶上县| 石柱| 海盐县| 潼南县| 湟源县| 阳江市| 闽侯县| SHOW| 蒙城县| 兴宁市| 堆龙德庆县| 禹城市| 陕西省| 贵南县| 崇信县| 阳原县| 左权县| 定州市| 东宁县| 比如县| 搜索| 科尔| 买车| 柯坪县| 洛宁县| 宝坻区| 那曲县| 涪陵区| 孝感市| 政和县| 宜兰县| 湟中县| 金乡县| 农安县|