Recursion in Swift

Posted by on Mar 21, 2016 in Apple, apps, code, programming, Swift | No Comments

Recursion is when a method or function calls itself.

//depending on what number you give to N, the function will call itself that many times, subtracting 1 from the original N each time through to pass as an argument.

func thisFunctionCallsItself(thisManyTimes: Int) {
    //The next few lines are to set up the proper suffix on the printed result string
    var mySuffix = String()
    //let's get the last two digits from thisManyTimes
    let lastTwoDigits = thisManyTimes % 100
    switch lastTwoDigits {
    case 10...20:
        mySuffix = "th"
        //get the last digit 
        let lastDigit = thisManyTimes % 10
        switch lastDigit {
        case 1:
            mySuffix = "st"
        case 2:
            mySuffix = "nd"
        case 3:
            mySuffix = "rd"
            mySuffix = "th"
    //OK that it.
    //below is where the function calls itself
    if thisManyTimes != 0 {
        thisFunctionCallsItself (thisManyTimes - 1)
        print("This is the \(thisManyTimes)\(mySuffix) time that this function has called itself.")

//call the function.


Email this to someoneTweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on StumbleUponShare on RedditDigg this

Leave a Reply