我正在尝试将 Paul Heggarty 为类(class) CS193p(斯坦福,2017 年冬季)创建的 Swift 计算器转换为 Typescript 代码(在本例中为 Ionic 3 (Angular 4)),以查看差异。
我并没有专注于尽可能多地以相同的方式做事。
我已经走了很远,但我正在努力用 typescript 做以下事情。
private var operations: Dictionary<String,Operation> = [
"+" : Operation.binaryOperation({ $0 + $1 }),
"−" : Operation.binaryOperation({ $0 - $1 }),
"÷" : Operation.binaryOperation({ $0 / $1 }),
"×" : Operation.binaryOperation({ $0 * $1 }),
"π" : Operation.constant(Double.pi),
"√" : Operation.preFixUnaryOperation(sqrt),
"x²" : Operation.postFixUnaryOperation({ pow($0, 2) }),
"x³" : Operation.postFixUnaryOperation({ pow($0, 3) }),
"=" : Operation.equals,
"±" : Operation.preFixUnaryOperation({ -$0 }),
"sin": Operation.preFixUnaryOperation(sin),
"cos": Operation.preFixUnaryOperation(cos),
"tan": Operation.preFixUnaryOperation(tan),
"e" : Operation.constant(M_E)
]
到目前为止,我所做的是创建一个私有(private)变量,名为“operations”,类型为“{}”。
然后通过调用“填充”它:
this.operations['+' = Operation.binaryOperation(() => {arguments[0] + argumenst[1]})
填充部分确实有效。除了我不知道如何解析这样的函数。
Swift 中的枚举操作:
private enum Operation {
case constant(Double)
case preFixUnaryOperation((Double) -> Double)
case postFixUnaryOperation((Double) -> Double)
case binaryOperation((Double,Double) -> Double)
case equals
}
Typescript 中的枚举操作(同样的问题):
export enum Operation {
constant, // Double is an assosiative value, its like the assosiated value in the 'set' state of an optional.
preFixUnaryOperation,
postFixUnaryOperation,
binaryOperation,
equals
}
我应该如何在 typescript/javascript 中使用在 Swift 中称为“闭包”的 a?
最佳答案
我想你的问题是关于 Associated Values ,而不是关于 Closures自己。
TypeScript 没有关联值的完整模拟,但您可以这样做:
const enum Operation {
preFixUnaryOperation,
postFixUnaryOperation,
binaryOperation
}
type IOperation = {
type: Operation.preFixUnaryOperation | Operation.postFixUnaryOperation;
func: (a: number) => number;
} | {
type: Operation.binaryOperation;
func: (a: number, b: number) => number;
}
let operations: {[key: string]: IOperation} = {
'+': { type: Operation.binaryOperation, func: (a, b) => a + b },
'x²': { type: Operation.postFixUnaryOperation, func: (a) => a * a }
};
let operation = operations[someKey];
switch (operation.type) {
case Operation.binaryOperation:
return operation.func(left, right);
case Operation.preFixUnaryOperation:
return operation.func(right);
case Operation.postFixUnaryOperation:
return operation.func(left);
}
另请参阅:Discriminated Unions
关于javascript - Typescript/Javascript 中的 Swift 闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46288928/