相关疑难解决方法(0)

如何将通用协议用作变量类型

假设我有一个协议:

public protocol Printable {
    typealias T
    func Print(val:T)
}
Run Code Online (Sandbox Code Playgroud)

这是实施

class Printer<T> : Printable {

    func Print(val: T) {
        println(val)
    }
}
Run Code Online (Sandbox Code Playgroud)

我的期望是我必须能够使用Printable变量来打印这样的值:

let p:Printable = Printer<Int>()
p.Print(67)
Run Code Online (Sandbox Code Playgroud)

编译器抱怨此错误:

"protocol'Printable'只能用作通用约束,因为它具有Self或相关的类型要求"

难道我做错了什么 ?有任何解决这个问题的方法吗 ?

**EDIT :** Adding similar code that works in C#

public interface IPrintable<T> 
{
    void Print(T val);
}

public class Printer<T> : IPrintable<T>
{
   public void Print(T val)
   {
      Console.WriteLine(val);
   }
}


//.... inside Main
.....
IPrintable<int> p = new Printer<int>();
p.Print(67)
Run Code Online (Sandbox Code Playgroud)

编辑2:我想要的真实世界的例子.请注意,这不会编译,但会呈现我想要实现的目标.

protocol Printable …
Run Code Online (Sandbox Code Playgroud)

generics xcode ios swift

81
推荐指数
2
解决办法
3万
查看次数

Swift 中的“存在类型”是什么意思?

我正在阅读Swift Evolution 提案 244(不透明结果类型),但不明白以下含义:

... 存在类型 ...

可以通过使用存在类型Shape 而不是泛型参数来组合这些转换,但这样做将意味着比预期更多的动态性和运行时开销。

type-theory swift

8
推荐指数
3
解决办法
1519
查看次数

通用类的Swift委托协议

我有一个类,StateMachine它是通用的,允许实现不同的状态集,例如,枚举.我想StateMachineDelegate在状态机进入新状态时使用协议通知委托.

但这不起作用,因为委托协议对于类型要求也是通用的.该错误显示了delegate声明属性的位置.

protocol StateType: Hashable {}

protocol StateMachineDelegate: class {
    typealias S: StateType
    func stateMachine(stateMachine: StateMachine<S>, didEnterState newState: S)
}

class StateMachine<S: StateType> {
    typealias State = S

    weak var delegate: StateMachineDelegate?
    //~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~
    //Protocol 'StateMachineDelegate' can only be used as a generic constraint because it has Self or associated type requirements

    var currentState: State {...}

    init(initialState: State) {...}

    func applyState(toState: State) -> Bool {
        ...
        currentState = toState
        delegate?.stateMachine(self, didEnterState: toState)
        ...
    }
} …
Run Code Online (Sandbox Code Playgroud)

generics delegates protocols swift

7
推荐指数
1
解决办法
1800
查看次数

标签 统计

swift ×3

generics ×2

delegates ×1

ios ×1

protocols ×1

type-theory ×1

xcode ×1