Swift generics and generic functions

Source: Internet
Author: User


Generics (generic) allow us to define a number of mutable parts in a program, specify at runtime, use generics to maximize code reuse, secure types of security, and improve performance.



1. Generic functions


After the function name is added <T>, the parameter type is also declared as t,t as a placeholder, and the function passes in the actual parameter type each time it is called to determine the type of T


Func log4<t> (msg:t) {

println (msg)


}



LOG4 (3)

LOG4 ("Sorry")

Log4 (1.02)


If there are several different types, you can use other uppercase letters, you are generally accustomed to using u, and multiple placeholders are separated by commas:


Examples are as follows:

Func isequals<t,u> (a:t,b:u)->bool {



}


Placeholders can override not only parameter types, but also return value types:


Func isequals<t,u> (a:t,b:u), t{}




2. Generic constraints


Some placeholders must follow a protocol, and the T placeholder is followed by a colon and a protocol type, which is represented as a generic constraint that can replace the type of T.


For example, a comparison function:


Func isequals<t> (A:t, b:t)->bool {

Return (A==B)

}

The above function will compile with an error because not all types are comparable, and the type T represents must conform to the type of the comparable protocol implementation, and the comparable protocol represents comparable:


Modify the following:


Func isequals<t:comparable> (A:t, b:t), Bool {

Return (A==B)


}




This article is from the "Ordinary Road" blog, please be sure to keep this source http://linjohn.blog.51cto.com/1026193/1620386

Swift generics and generic functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.