当前位置:网站首页>Use of swift generics
Use of swift generics
2022-04-22 02:26:00 【Autumn trifles】
//
// Paradigm.swift
// SwiftCode
//
// Created by Alisa on 2022/4/13.
// Copyright 2022 Alisa. All rights reserved.
//
import Foundation
/*
** The role and usage scenario of generics
Generics are often used to express an undetermined data type
The role of generics : Paradigm is a characteristic of programming language , Allows developers to define variable parts when writing code in strongly typed programming languages
A usage scenario for generics :
We need to write a function , If this function has parameters , Usually we need to specify the type of parameter . Now we're going to write such a function , Its function will be on two inout And the parameters of the same type exchange values , The functional requirements of this function do not require the specific type of parameters , Just the same type , For such needs , Developers will not and cannot use overloading to implement all functions corresponding to data types , Generics can solve this kind of problem
** The use of generics in functions and collections
Generics as function parameters : Use... Before the function argument list <>, List the generic types to be defined , Its scope is the parameter list of the function and the whole function implementation part , If you want to define multiple generics in a function ,
Use commas to separate .
The use of generics in collections : In a statement Array or Dictionary When this kind of set type , Developers can set the element types to be stored in these collection types at the same time , We can also use generics to achieve
** Constrain generics
swift You can constrain generics in two ways :
<1> By inheriting the base class or following the protocol
<2> adopt where Clause to constrain
Use inheritance to constrain generic types , The constraint that the generic type must be implemented through a base class or a subclass inherited from a base class
Constrain generics in a protocol compliant manner , Some unimplemented methods and properties can be defined in the protocol , The types that comply with this protocol need to implement the methods and properties defined therein
Generics also have special applications in protocols , When creating an agreement , have access to associatetype Keyword to associate generic types , When a data type implements this protocol , This association is generic
The specific type will be specified
Use where Clause combined with generics , You can add more stringent type constraints to generics
*/
class FirstAcquaintance{
// Use generics , Define a function , Exchange the two values passed in
func exchange<T>(param1: inout T, param2: inout T){
let tmp = param1
param1 = param2
param2 = tmp
print(" Data after exchange :param1: \(param1), param2: \(param2)")
}
}
// Use generics to define the type of an element , Implement a simple stack function , The feature of the stack is : First in, then out
struct Stack<ItemType>{
// All internal operations related to element types use ItemType
var items:[ItemType] = []
mutating func push(param:ItemType){
self.items.append(param)
print(" Stack the array :\(self.items)")
}
//mutating Modifier function is used to change the attribute of value type , But it can only be used for instance methods that modify structures
mutating func pop()->ItemType{ // Used to modify class Method time :'mutating' is not valid on instance methods in classes
return self.items.removeLast()
}
}
// Use inheritance to constrain generics
class Bread{
var typeName:String
func bakeInOven(){
print("This bread will bake into the oven.")
}
init(typeName:String) {
self.typeName = typeName
}
}
struct Oven<ItemType:Bread>{
var bread:ItemType
mutating func baking(){
print(" Put the bread :\(bread.typeName) Bake in the oven ")
}
}
// Use protocols to constrain generics
protocol Food{
// The type is specified only when the protocol is implemented
associatedtype ItemType
// The agreement stipulates that ItemType The computed property of type
var food:ItemType {get set}
// A method is agreed in the agreement
func heatFoodInPot(param:ItemType)->Void
// Be careful
// A value attribute is agreed in the protocol , This directly declared value attribute is not allowed , You must use the method of calculating attributes
//var foodName:ItemType //Property in protocol must have explicit { get } or { get set } specifier
}
class Milk{
var name:String = "Milk"
}
// Define a compliance Food Protocol class
class Pot:Food{
var food:Milk = Milk()
var foodType:Milk{
get{
return self.food
}
set{
self.food = newValue
}
}
func heatFoodInPot(param: Milk) {
print("Now heat the \(food.name) in this pot!")
}
}
// Use where Clause constrains generics
class WhereBox<B,M> where B:Bread, M:Milk{
var foodOne:B
var foodTwo:M
init(foodOne:B, foodTwo:M){
self.foodOne = foodOne
self.foodTwo = foodTwo
}
func boxFood(){
print("This box has \(foodOne.typeName) and \(foodTwo.name)")
}
}
class Paradigm{
// Generics as arguments to functions
func useInMethod(){
var p1 = "15"
var p2 = "40"
let fav = FirstAcquaintance()
fav.exchange(param1: &p1, param2: &p2)
// Print data : Data after exchange :param1: 40, param2: 15
}
// Generics define the types of elements
func useInElement(){
// Integer stack
var one = Stack<Int>()
one.push(param: 2)
one.push(param: 4)
one.push(param: 6)
one.push(param: 8)
one.push(param: 10)
one.push(param: 12)
one.push(param: 14)
let oneA = one.pop()
print(" Integer stack : Out of stack elements :\(oneA), Array after stack :\(one.items)")
// String stack
var two = Stack<String>()
two.push(param: "one")
two.push(param: "two")
two.push(param: "three")
two.push(param: "four")
two.push(param: "five")
two.push(param: "six")
let twoA = two.pop()
print(" String stack : Out of stack elements :\(twoA), Array after stack :\(two.items)")
/* Print data :
Stack the array :[2]
Stack the array :[2, 4]
Stack the array :[2, 4, 6]
Stack the array :[2, 4, 6, 8]
Stack the array :[2, 4, 6, 8, 10]
Stack the array :[2, 4, 6, 8, 10, 12]
Stack the array :[2, 4, 6, 8, 10, 12, 14]
Integer stack : Out of stack elements :14, Array after stack :[2, 4, 6, 8, 10, 12]
Stack the array :["one"]
Stack the array :["one", "two"]
Stack the array :["one", "two", "three"]
Stack the array :["one", "two", "three", "four"]
Stack the array :["one", "two", "three", "four", "five"]
Stack the array :["one", "two", "three", "four", "five", "six"]
String stack : Out of stack elements :six, Array after stack :["one", "two", "three", "four", "five"]
*/
}
// Use inheritance to constrain generics
func useInheritance(){
let bread = Bread(typeName: "Buttered Toast")
bread.bakeInOven()
var oven = Oven(bread: bread)
oven.baking()
/* Print information
This bread will bake into the oven.
Put the bread :Buttered Toast Bake in the oven
*/
}
// Use protocols to constrain generics
func useProtocol(){
let milk = Milk()
milk.name = "Milk Deluxe"
let pot = Pot()
pot.foodType = milk
pot.heatFoodInPot(param: pot.foodType)
/* Print information
Now heat the Milk Deluxe in this pot!
*/
}
// Use where Clause constrains generics
func useWhere(){
let bread = Bread(typeName: "Buttered Toast")
let milk = Milk()
milk.name = "Milk Deluxe"
let wh = WhereBox(foodOne: bread, foodTwo: milk)
wh.boxFood()
/* Print information
This box has Buttered Toast and Milk Deluxe
*/
}
}
版权声明
本文为[Autumn trifles]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220224331589.html
边栏推荐
- 单层神经⽹络的详细实现
- Explain various cloud computing models in detail. How can enterprises use each model to improve business productivity?
- Eight common probability distribution formulas and visualization
- AI application theory - Smart farm (cattle farm without monitoring)
- PV-TSM原理及matlab仿真
- SV知识点回顾
- Swift 泛型的使用
- 【查看已经安装的包和命令是由哪个包提供的】
- 高级UI都没弄明白凭什么拿高薪,劲爆
- CAN初始化流程
猜你喜欢

Redis cache database uses redis shake for data synchronization

嵌入式AI
![[论文阅读] Active Class Incremental Learning for Imbalanced Datasets](/img/20/ecfffcdeed6813a6bdb703794a2607.png)
[论文阅读] Active Class Incremental Learning for Imbalanced Datasets

Alibaba P9 explains high concurrency in detail, and shows you how Taobao can resist large-scale second kill activities such as double 11

Application and principle analysis of ThreadLocal

Explain the mathematical process of neural network like a pile of LEGO

像堆乐高一样解释神经网络的数学过程

Plug in import and usage of uni list
![[check which package provides the installed packages and commands]](/img/d8/ce76b177937b46c12469ea2bddf565.png)
[check which package provides the installed packages and commands]

Pycharm同时执行多个脚本文件
随机推荐
centos7安装mysql5.7的详细教程
What about first-class insurance? Is there a charge? What are the waiting requirements?
DEJA_ Vu3d - cesium feature set 013 - military plotting Series 7: regular polygon
Shell基础语法
CentOS 7 installs mysql5 7 detailed tutorial
The shortcut key for modifying the drawing board size of illustrator (AI) is shift + O by default
Target motion model - uniform motion CV
CTF wiki local construction record
Tensorflow 2.x(keras)源码详解之第五章:数据预处理
Unity game optimization - third edition reading notes Chapter 1 analyze performance problems
Review of SV knowledge points
MySQL cannot find my INI file
基于Hikari连接池的对数据库进行增删查改的通用工具类
Why won't MySQL lose data when the power is suddenly off? (Collection)
From the DX level, WPF rendering Caton
Pychar executes multiple script files at the same time
68 smart pipe gallery project construction solution
Page 78 digital twin + smart building solutions
Solve the problem that the search box of select2 in modal is invalid
Window7 activation phone activation notes;