斯威夫特泛型协议的N种用法

澳门葡京备用网址,  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!

  本篇纯属抬杠之作,在此以前大家关系了斯威夫特的泛型Protocol使用associatedtype关键字,而不是运用<Type>语法的泛型参数。那里面有如何收益吗?

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

  这几个笑话绝对是自个儿看过的斯维夫特被黑的最惨的3遍!所现在天我们来学学一下Swift的泛型。

  那些笑话相对是本人看过的Swift被黑的最惨的3次!所在此以前几日大家来读书一下斯威夫特的泛型。

  笔者就以此主题材料查找了有的答应,大要上关系两点:

  笔者就那几个标题查找了有个别作答,大要上提到两点:

  Swift的泛型有点意料之外,针对Class和Function,都以由此<Type>来定义,和C#一摸同样,一样也有where关键字张开约束。

  斯威夫特的泛型有点意想不到,针对Class和Function,都以通过<Type>来定义,和C#一摸同样,同样也有where关键字展开约束。

  <Type>语法对Protocol没风趣,Protocol仅供给定义一个浮泛的定义,具体的花色应该由实现的Class来家弦户诵,举个例子:

  <Type>语法对Protocol未有意义,Protocol仅须求定义一个浮泛的概念,具体的品种应该由落成的Class来深入人心,比方:

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 {}
}
ClassWithInt<Int>: NumberProtocol
ClassWithDouble<Double>: NumberProtocol
ClassWithInt<Int>: NumberProtocol
ClassWithDouble<Double>: NumberProtocol

  但是面对Interface,也等于Swift里的Protocol,要求使用associatedtype关键字来定义泛型:

  然则面对Interface,也正是Swift里的Protocol,须求采纳associatedtype关键字来定义泛型:

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

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

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

  那要怎么去得以完毕这些接口呢?常常是那样子的:

  那要怎么去贯彻那一个接口呢?平时是那样子的:

  听上去依旧有自然道理的,然后施行是查看事实的唯一标准。上边大家通过代码实例来和C#进展自己检查自纠。首先拿出网络多被引述解释上述多个意见的Swift代码:

  听上去依然有自然道理的,然后施行是查证事实的唯一标准。上面我们由此代码实例来和C#斯威夫特泛型协议的N种用法。进展对照。首先拿出英特网多被引述解释上述七个视角的Swift代码:

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")
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()
    }
}

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

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

  具体的应用状态如下:

  具体的接纳情形如下:

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

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

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()

  曲线救国的话,大家得以思索模拟三个架空类class
CanPrintBase<T>,通过一而再来促成平等的效应:

  曲线救国的话,大家得以思索模拟三个虚无类class
CanPrintBase<T>,通过一而再来完结平等的作用:

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

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

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")
    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();
        }
    }

  那么我们像C#平等一贯在类定义的时候经过占位符的艺术得以嘛?

  那么大家像C#同1直接在类定义的时候经过占位符的点子得以嘛?

  还是能效仿Swift对Automobile多做壹层承袭进行打包:

  仍是能够效仿Swift对Automobile多做壹层承继举行打包:

//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)
    }
}
    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();
        }
    }

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

  错误提醒为:Inheritance from non-protocol,
non-class type ‘String’。相当于说假设是class类型的话就能够:

调用的时候从不什么太大的分裂:

调用的时候没有何太大的异样:

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())
  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();

  反之我们也得以写成那样:

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

  和斯威夫特相比较区别的是,大家在Interface就代入了泛型参数。不过出于大家无法直接实例化Interface,所以并无法直接动用Automobile来压缩一层承袭关系。

  和斯维夫特比较差别的是,大家在Interface就代入了泛型参数。可是出于大家无法直接实例化Interface,所以并不可能一贯利用Automobile来压缩壹层承袭关系。

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))

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

  因为上述提到的应用associatedtype 的第二点理由见仁见智,那里不分高下。

  将品种打字与印刷出来的话,分别是TypePrinter伍和TypePrinter二<SomeType>,也正是说那三种写法获得的项目是完全差异的。

  将项目打字与印刷出来的话,分别是TypePrinter五和TypePrinter贰<SomeType>,也正是说那三种写法获得的类型是全然不平等的。

  C#还有第二种思路,正是自个儿也把泛型约束下放到Func层级:

  C#还有第3种思路,就是笔者也把泛型约束下放到Func层级:

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

  呵呵也是蛮妖的嘛,还足以把品种的实际定义留到使用时再声称:

    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>();
        }
    }
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")

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

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

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

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

    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();

  本篇实在是蛮无聊的纠缠与斯威夫特泛型协议的语法,如孔乙己般尝试了回字的N种写法。至于为什么Swift要如此设计,我们下一篇可以品味和C#对照顾看。

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

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

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

  GitHub:

  GitHub:

  GitHub:

  GitHub:

  

  

 

 

 

 

 

 

 

 

相关文章

发表评论

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

*
*
Website