如何使用通用类执行递归方法
我有一个具有一个函数的类,可以在不使用Build-In方法的情况下进行乘法。我可以在不使用通用的情况下使我的功能工作,但是我可以在使用通用的同时使它起作用。我的问题是,每次尝试调用它时,我的递归呼叫功能都会给我一个错误。有反馈吗?
我的错误是:线程1:exc_bad_access(代码= 2,地址= 0x7ff7bc42af70)
class Math5<T: Numeric> {
func multiplier(_ a: T, _ b: T) -> T {
if a == 0 || b == 0 {
return 0;
} else {
return a + multiplier(a, b - 1)
}
}
}
I have a class that has one function that does multiplication without using build-in methods. I got my function to work without using a generic, but I can get it to work while using a generic. My problem is my recursive call-back function is giving me an error each time I try and call it. Any feedback?
my error is : Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ff7bc42af70)
class Math5<T: Numeric> {
func multiplier(_ a: T, _ b: T) -> T {
if a == 0 || b == 0 {
return 0;
} else {
return a + multiplier(a, b - 1)
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅当
b
是一个非负整数时,您的乘法算法才有效。如果b
是负面的,或者包含一个分数,则b == 0
永远不会变为真。如果您至少将类型t
限制为unignedInteger
,则编译器在编译时执行这些限制:您可以概括以使第一个参数可以是任何
addiviveArithmetic
仅允许unsignedInteger
用于第二个参数。让我们删除类
并使用免费功能:如果您以
B
的足够大价值传递,则仍然可以使用堆栈溢出崩溃。由于Swift不能保证消除尾声,因此您还应该更改算法以使用循环而不是递归,如果您想避免堆叠溢出。Your multiplication algorithm is only valid if
b
is a non-negative integer. Ifb
is negative, or includes a fraction, thenb == 0
will never become true. If you at least constrain typeT
toUnsignedInteger
, then the compiler enforces those limitations at compile-time:You can generalize so that the first argument can be any
AdditiveArithmetic
while only allowing anUnsignedInteger
for the second argument. Let's drop theclass
and use a free function:You can still crash with a stack overflow if you pass in a large enough value for
b
. Since Swift doesn't guarantee tail call elimination, you should also change your algorithm to use a loop instead of recursion if you want to avoid stack overflows.使函数通用
相同的实现
Make the function generic
Same implementation