简体   繁体   English

XCode Playground (Swift) 中的递归函数

[英]Recursive function in XCode Playground (Swift)

I'm learning recursive functions in Swift, and I did the following:我正在 Swift 中学习递归函数,我做了以下事情:

func recursive(i: Int) -> Int {
    if i == 1 {
        return 1
    } else if i >= 2 {
        return recursive(i: i - 1) + 1
    }
    return 0
}

I couldn't figure out why the function above is not working.我无法弄清楚为什么上面的功能不起作用。 I've tested it by doing the below doing print(recursive(10)) , which gives me an output of 10. I expected the output to be 1. Can anyone help me with this?我已经通过执行以下操作来测试它print(recursive(10)) ,这给了我 10 的输出。我希望输出为 1。有人可以帮我吗? Thank you in advance.先感谢您。

I'm using Playgrounds on XCode 8.3.我在 XCode 8.3 上使用 Playgrounds。

When you do this:当你这样做时:

recursive(i: i - 1) + 1

… then you are in effect decrementing i and then incrementing it again. ……那么你实际上是在减少i然后再次增加它。 That cancels out and you arrive at i again.这取消了,你再次到达i

Let's write down what calculation would be done for i = 3 :让我们写下对i = 3进行的计算:

(3 - 1) + 1 = ((2 - 1) + 1) + 1 = (((1) + 1) + 1) = 3

This is a perfect example of printing numbers without using any loop.这是不使用任何循环打印数字的完美示例。

The recursive functions are very useful to handle such cases.递归函数对于处理这种情况非常有用。

func printCount( count : inout Int , limit : Int) {
    
    print(count, terminator: " ")
    count += 1  
    if count  > limit {
        return
    }
    
    printCount(count: &count , limit: limit)
}

var count = 11
let limit = 20
printCount(count: &count , limit: limit)

Output : 11 12 13 14 15 16 17 18 19 20输出:11 12 13 14 15 16 17 18 19 20

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM