Swift泛型协议的N种用法

  本篇纯属抬杠之作,此前大家关系了斯维夫特的泛型Protocol使用associatedtype关键字,而不是选拔<Type>语法的泛型参数。这几个中有何样利润呢?

  本篇纯属抬杠之作,在此以前大家关系了斯维夫特的泛型Protocol使用associatedtype关键字,而不是使用<Type>语法的泛型参数。那在那之中有何好处呢?

  They said “you should learn a new language every year,” so I 
learned Swift. Now  I  learn a new language every two weeks!

  They said “you should learn a new language every year,” so I 
learned Swift. Now  I  learn a new language every two weeks!

  作者就那几个难题查找了有的回复,大要上涉及两点:

  笔者就以此主题材料查找了有的回应,概略上关系两点:

  这些笑话相对是自身看过的Swift被黑的最惨的2遍!所以明天我们来学习一下Swift的泛型。

  那个笑话相对是本人看过的Swift被黑的最惨的一遍!所从前几日我们来读书一下斯维夫特的泛型。

  <Type>语法对Protocol未有意义,Protocol仅要求定义1个空洞的概念,具体的品种应该由落成的Class来分明,举例:

  <Type>语法对Protocol未有意义,Protocol仅要求定义一个华而不实的概念,具体的门类应该由达成的Class来显明,比如:

  Swift的泛型有点出乎意料,针对Class和Function,都以由此<Type>来定义,和C#1摸同样,一样也有where关键字展淮南锁。

  斯威夫特的泛型有点难以置信,针对Class和Function,都以透过<Type>来定义,和C#壹摸同样,一样也有where关键字张开约束。

ClassWithInt<Int>: NumberProtocol
ClassWithDouble<Double>: NumberProtocol
ClassWithInt<Int>: NumberProtocol
ClassWithDouble<Double>: NumberProtocol
func swapTwoValues<T>(inout a: T, inout _ b: T) {
    let temporaryA = a
    a = b
    b = temporaryA
}

class CanPrintBase<T> {
    func PrintType(output: T) -> Void {}
}
func swapTwoValues<T>(inout a: T, inout _ b: T) {
    let temporaryA = a
    a = b
    b = temporaryA
}

class CanPrintBase<T> {
    func PrintType(output: T) -> Void {}
}

  associatedtype能够用来给Protocol中特定Func增添泛型约束,而不是限制整个Protocol

  associatedtype能够用来给Protocol中特定Func增多泛型约束,而不是限制整个Protocol

Swift泛型协议的N种用法。  但是面对Interface,也便是斯维夫特里的Protocol,要求选拔associatedtype关键字来定义泛型:

  可是面对Interface,也正是Swift里的Protocol,需求使用associatedtype关键字来定义泛型:

protocol GeneratorType {
    associatedtype Element
    public mutating func next() -> Self.Element?
}
protocol GeneratorType {
    associatedtype Element
    public mutating func next() -> Self.Element?
}
protocol CanPrint {
    
    associatedtype E
    
    func PrintType(output: E) -> Void
}
protocol CanPrint {
    
    associatedtype E
    
    func PrintType(output: E) -> Void
}

  听上去依然有确定道理的,然后施行是查验事实的唯1规范。下边大家通过代码实例来和C#展开对照。首先拿出英特网多被引述解释上述多个视角的斯威夫特代码:

  听上去依然有早晚道理的,然后试行是检察事实的唯壹标准。下边大家通过代码实例来和C#举办对照。首先拿出互连网多被引述解释上述四个视角的Swift代码:

  那要怎么去得以达成那几个接口呢?平时是那样子的:

  那要怎么去达成那么些接口呢?经常是那样子的:

public protocol Automobile {
    associatedtype FuelType
    associatedtype ExhaustType
    func drive(fuel: FuelType) -> ExhaustType
}
public protocol Fuel {
    associatedtype ExhaustType
    func consume() -> ExhaustType
}
public protocol Exhaust {
    init()
    func emit()
}

public struct UnleadedGasoline<E: Exhaust>: Fuel {
    public func consume() -> E {
        print("...consuming unleaded gas...")
        return E()
    }
}
public struct CleanExhaust: Exhaust {
    public init() {}
    public func emit() {
        print("...this is some clean exhaust...")
    }
}
public class Car<F: Fuel,E: Exhaust>: Automobile where F.ExhaustType == E {
    public func drive(fuel: F) -> E {
        return fuel.consume()
    }
}

public class Car1<F: Fuel>: Automobile {
    public func drive(fuel: F) -> F.ExhaustType {
        return fuel.consume()
    }
}
public protocol Automobile {
    associatedtype FuelType
    associatedtype ExhaustType
    func drive(fuel: FuelType) -> ExhaustType
}
public protocol Fuel {
    associatedtype ExhaustType
    func consume() -> ExhaustType
}
public protocol Exhaust {
    init()
    func emit()
}

public struct UnleadedGasoline<E: Exhaust>: Fuel {
    public func consume() -> E {
        print("...consuming unleaded gas...")
        return E()
    }
}
public struct CleanExhaust: Exhaust {
    public init() {}
    public func emit() {
        print("...this is some clean exhaust...")
    }
}
public class Car<F: Fuel,E: Exhaust>: Automobile where F.ExhaustType == E {
    public func drive(fuel: F) -> E {
        return fuel.consume()
    }
}

public class Car1<F: Fuel>: Automobile {
    public func drive(fuel: F) -> F.ExhaustType {
        return fuel.consume()
    }
}
class TypePrinter0 : CanPrint{
    
    typealias E = String
    
    func PrintType(output: E) {
        print(type(of:output))
    }
}

let print0 = TypePrinter0()
print0.PrintType(output: "String Type")
class TypePrinter0 : CanPrint{
    
    typealias E = String
    
    func PrintType(output: E) {
        print(type(of:output))
    }
}

let print0 = TypePrinter0()
print0.PrintType(output: "String Type")

  具体的采用情况如下:

  具体的利用境况如下:

  然后就会在output窗口打字与印刷“String”。

  然后就会在output窗口打字与印刷“String”。

var car = Car<UnleadedGasoline<CleanExhaust>, CleanExhaust>()
car.drive(fuel: UnleadedGasoline<CleanExhaust>()).emit()

var fusion = Car1<UnleadedGasoline<CleanExhaust>>()
fusion.drive(fuel: UnleadedGasoline<CleanExhaust>()).emit()
var car = Car<UnleadedGasoline<CleanExhaust>, CleanExhaust>()
car.drive(fuel: UnleadedGasoline<CleanExhaust>()).emit()

var fusion = Car1<UnleadedGasoline<CleanExhaust>>()
fusion.drive(fuel: UnleadedGasoline<CleanExhaust>()).emit()

  阿西吧!这么意料之外的语法简直不能够忍!就无法用<Type>来写吧?

  阿西吧!这么意料之外的语法大概无法忍!就不能用<Type>来写啊?

  转换成C#代码的话,有三种思路,首先是把泛型参数放到Interface层面:

  转换成C#代码的话,有三种思路,首先是把泛型参数放到Interface层面:

  曲线救国的话,我们得以思索模拟3个虚幻类class
CanPrintBase<T>,通过接二连三来促成均等的成效:

  曲线救国的话,我们得以思量模拟三个浮泛类class
CanPrintBase<T>,通过一而再来完结均等的效应:

    public interface Automobile<FuelType, ExhaustType>
    {
        ExhaustType Drive(FuelType fuel);
    }
    public interface Fuel<ExhaustType>
    {
        ExhaustType consume();
    }
    public interface Exhaust 
    {
        void Emit();
    }

    public class UnleadedGasoline<Exhaust> : Fuel<Exhaust> where Exhaust : new()
    {
        public Exhaust consume()
        {
            Console.WriteLine("...consuming unleaded gas...");
            return new Exhaust();
        }
    }
    public class CleanExhaust : Exhaust
    {
        public void Emit()
        {
            Console.WriteLine("...this is some clean exhaust...");
        }
    }
    public class Car : Automobile<UnleadedGasoline<CleanExhaust>, CleanExhaust>
    {
        public CleanExhaust Drive(UnleadedGasoline<CleanExhaust> fuel)
        {
            return fuel.consume();
        }
    }
    public interface Automobile<FuelType, ExhaustType>
    {
        ExhaustType Drive(FuelType fuel);
    }
    public interface Fuel<ExhaustType>
    {
        ExhaustType consume();
    }
    public interface Exhaust 
    {
        void Emit();
    }

    public class UnleadedGasoline<Exhaust> : Fuel<Exhaust> where Exhaust : new()
    {
        public Exhaust consume()
        {
            Console.WriteLine("...consuming unleaded gas...");
            return new Exhaust();
        }
    }
    public class CleanExhaust : Exhaust
    {
        public void Emit()
        {
            Console.WriteLine("...this is some clean exhaust...");
        }
    }
    public class Car : Automobile<UnleadedGasoline<CleanExhaust>, CleanExhaust>
    {
        public CleanExhaust Drive(UnleadedGasoline<CleanExhaust> fuel)
        {
            return fuel.consume();
        }
    }
class TypePrinter3: CanPrintBase<String>{
    
    override func PrintType(output: String){
         print(type(of:output))
    }
}

let print3 = TypePrinter3()
print3.PrintType(output: "String Type")
class TypePrinter3: CanPrintBase<String>{
    
    override func PrintType(output: String){
         print(type(of:output))
    }
}

let print3 = TypePrinter3()
print3.PrintType(output: "String Type")

  还是能照猫画虎Swift对Automobile多做一层承接举办打包:

  还能效仿斯威夫特对Automobile多做一层承袭举行打包:

  那么我们像C#同等直接在类定义的时候经过占位符的措施得以嘛?

  那么大家像C#同样一贯在类定义的时候经过占位符的法子得以嘛?

    public interface Car1<T1> : Automobile<UnleadedGasoline<T1>, T1> where T1 : new()
    {

    }

    public class SimpleCar : Car1<CleanExhaust>
    {
        public CleanExhaust Drive(UnleadedGasoline<CleanExhaust> fuel)
        {
            return fuel.consume();
        }
    }
    public interface Car1<T1> : Automobile<UnleadedGasoline<T1>, T1> where T1 : new()
    {

    }

    public class SimpleCar : Car1<CleanExhaust>
    {
        public CleanExhaust Drive(UnleadedGasoline<CleanExhaust> fuel)
        {
            return fuel.consume();
        }
    }
//This one cannot work!
class TypePrinter1<E: String> : CanPrint{
   
    func PrintType(output: E) {
        print(output)
    }
}
//This one cannot work!
class TypePrinter1<E: String> : CanPrint{
   
    func PrintType(output: E) {
        print(output)
    }
}

调用的时候从不怎么太大的差别:

调用的时候未有怎么太大的异样:

  错误提醒为:Inheritance from non-protocol,
non-class type ‘String’。也正是说如若是class类型的话就足以:

  错误提示为:Inheritance from non-protocol,
non-class type ‘String’。也便是说假如是class类型的话就足以:

  var gaso = new UnleadedGasoline<CleanExhaust>();
  var car = new Car();
  car.Drive(gaso).Emit();

  var simpleCar = new SimpleCar();
  simpleCar.Drive(gaso).Emit();
  var gaso = new UnleadedGasoline<CleanExhaust>();
  var car = new Car();
  car.Drive(gaso).Emit();

  var simpleCar = new SimpleCar();
  simpleCar.Drive(gaso).Emit();
public class SomeType {}

class TypePrinter2<E: SomeType> : CanPrint{

    func PrintType(output: E) {
        print(output)
    }

}

let print2 = TypePrinter2()
print2.PrintType(output: SomeType())
public class SomeType {}

class TypePrinter2<E: SomeType> : CanPrint{

    func PrintType(output: E) {
        print(output)
    }

}

let print2 = TypePrinter2()
print2.PrintType(output: SomeType())

  和斯威夫特相比较差异的是,大家在Interface就代入了泛型参数。但是由于大家不能够直接实例化Interface,所以并不可能平素运用Automobile来缩短壹层承继关系。

  和斯威夫特比较差别的是,大家在Interface就代入了泛型参数。不过由于我们无法直接实例化Interface,所以并不能够一贯动用Automobile来减弱一层承接关系。

  反之我们也得以写成这么:

  反之大家也得以写成这样:

  因为上述提到的选取associatedtype 的第一点理由见仁见智,这里不分高下。

  因为上述提到的选择associatedtype 的首先点理由见仁见智,那里不分高下。

class TypePrinter5 : CanPrint{
    
    typealias E = SomeType
    
    func PrintType(output: E) {
        print(output)
    }
}

let print5 = TypePrinter5();
print(type(of: print5))
print(type(of: print2))
class TypePrinter5 : CanPrint{
    
    typealias E = SomeType
    
    func PrintType(output: E) {
        print(output)
    }
}

let print5 = TypePrinter5();
print(type(of: print5))
print(type(of: print2))

  C#再有第二种思路,就是本人也把泛型约束下放到Func层级:

  C#澳门葡京备用网址 ,还有第二种思路,就是自个儿也把泛型约束下放到Func层级:

  将品种打印出来的话,分别是TypePrinter5和TypePrinter贰<SomeType>,也便是说那三种写法得到的门类是完全不等同的。

  将项目打字与印刷出来的话,分别是TypePrinter5和TypePrinter二<SomeType>,约等于说那三种写法获得的体系是南辕北辙样的。

    public interface Automobile
    {
        ExhaustType Drive<FuelType,ExhaustType>(FuelType fuel) where ExhaustType : new();
    }
    public interface Fuel
    {
        ExhaustType consume<ExhaustType>() where ExhaustType : new();
    }

    public class UnleadedGasoline : Fuel
    {
        public Exhaust consume<Exhaust>() where Exhaust : new()
        {
            Console.WriteLine("...consuming unleaded gas...");
            return new Exhaust();
        }
    }

    public class Car2 : Automobile
    {
        public CleanExhaust Drive<UnleadedGasoline, CleanExhaust>(UnleadedGasoline fuel) where CleanExhaust : new()
        {
            return  (fuel as Fuel).consume<CleanExhaust>();
        }
    }
    public interface Automobile
    {
        ExhaustType Drive<FuelType,ExhaustType>(FuelType fuel) where ExhaustType : new();
    }
    public interface Fuel
    {
        ExhaustType consume<ExhaustType>() where ExhaustType : new();
    }

    public class UnleadedGasoline : Fuel
    {
        public Exhaust consume<Exhaust>() where Exhaust : new()
        {
            Console.WriteLine("...consuming unleaded gas...");
            return new Exhaust();
        }
    }

    public class Car2 : Automobile
    {
        public CleanExhaust Drive<UnleadedGasoline, CleanExhaust>(UnleadedGasoline fuel) where CleanExhaust : new()
        {
            return  (fuel as Fuel).consume<CleanExhaust>();
        }
    }

  呵呵也是蛮妖的嘛,还能把项目标现实性定义留到使用时再注解:

  呵呵也是蛮妖的嘛,还足以把项目标求实定义留到使用时再表明:

C#的接口并不可能定义构造函数。强行模仿起来还真是有点累啊。最后的接纳也很简短:

C#的接口并不能够定义构造函数。强行模仿起来还真是有点累啊。最后的应用也很简短:

class TypePrinter4<E> : CanPrint{
    
    func PrintType(output: E) {
        print(output)
    }
}
let print4 = TypePrinter4<SomeType>()
print4.PrintType(output: SomeType())

let print6 = TypePrinter4<String>()
print6.PrintType(output: "I am a String")
class TypePrinter4<E> : CanPrint{
    
    func PrintType(output: E) {
        print(output)
    }
}
let print4 = TypePrinter4<SomeType>()
print4.PrintType(output: SomeType())

let print6 = TypePrinter4<String>()
print6.PrintType(output: "I am a String")
    var fuel = new UnleadedGasoline();
    var car2 = new Car2();
    car2.Drive<UnleadedGasoline,CleanExhaust>(fuel).Emit();
    var fuel = new UnleadedGasoline();
    var car2 = new Car2();
    car2.Drive<UnleadedGasoline,CleanExhaust>(fuel).Emit();

  这点又和C#傻傻分不清楚了。

  那点又和C#傻傻分不清楚了。

  通篇相比下来,应该说Swift通过associatedtype 关键字和<Type>的混用,使得泛型的定义更为复杂也越来越灵活了。

  通篇相比较下来,应该说Swift通过associatedtype 关键字和<Type>的混用,使得泛型的概念更为复杂也越来越灵活了。

  本篇实在是蛮无聊的纠缠与Swift泛型协议的语法,如孔乙己般尝试了回字的N种写法。至于缘何斯威夫特要如此设计,大家下1篇能够尝尝和C#比较之下看看。

  本篇实在是蛮无聊的缠绕与Swift泛型协议的语法,如孔乙己般尝试了回字的N种写法。至于怎么斯威夫特要如此设计,大家下一篇能够品尝和C#对待看看。

  GitHub:

  GitHub:

  GitHub:

  GitHub:

  

  

 

 

 

 

 

 

 

 

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*
*
Website