rohanKumar rohanKumar - 4 months ago 7
Swift Question

Swift playground and LeetCode OJ

class Solution {
func reverseString(s: String) -> String {
let rev = String(s.characters.reverse())
print(rev)
}
}


The error i get is:
Missing return in a function expected to return String

The same function in Leetcode OJ gives me the following error:

Line 4: cannot call value of non-function type 'Distance' (aka 'Int')

While i type the following in the Playground it works fine:

var str = "Hello"
let rev = String(str.characters.reverse())


I can't seem to figure out the solution to this and why it behaves differently in the playground with the function return type and in Leetcode OJ.

Swift noob and any help would be most appreciated! thanks

Answer

Try this:

class Solution {
func reverseString(s: String) -> String {
    let rev = String(s.characters.reverse())
    print(rev)
    return rev
    }
}

var str = Solution()
str.reverseString("Hello")

If you intend to add custom methods which works on a a particular Type than create an extension on that Type type.

extension String {
    // you methods
}

For example:

extension String {
    func length() -> Int {
        return self.characters.count
    }
}

Then you can use it as class function on String type

let greetings: String = "Hello"
greetings.length()  // 5