I watch a lesson on Swift and there they show such an example.

func sayHi() -> String{ return "hi" } func doSmth(smth : () -> (String)){ print(smth) } doSmth(smth: sayHi()) 

and everything works, but when I write the same thing myself, I get this error

enter image description here

I understand that I have a later version of the swift than is used in the example, but then how can I betray the function as a parameter?

    1 answer 1

    Fixed :)

     func sayHi() -> String{ return "hi" } func doSmth(smth : () -> (String)){ print(smth()) } doSmth(smth: sayHi) 

    it looks like you just put brackets in the wrong place.

    If more detail - doSmth expects to get the function, and adding brackets, you pass it the result of the function. Actually, the compiler curses it - it cannot convert the string (the one that sayHi returns) into a function of the form '() -> (String)', which doSmth wants.

    Inside the function doSmth smth is a function and needs to be called. For this there are needed brackets.

    • Well, it seems that it is indeed strange. The same function also means that it should be called it should says() with parentheses ... but how can you understand this function or the value of doSmth(smth: sayHi) this is how you will say on this line I pass the function or value as a parameter? And the second is also strange in the doSmth() function and doSmth() as the smth parameter without brackets, and when we call print(smth()) with brackets ... Why? And what if the brackets are not put then I get in the log instead of hi , (Function) what does it mean? - Aleksey Timoshchenko
    • These are all so-called higher order functions. Simply put, when the type of a variable can be a function, and the value is a specific function. If you just pass a function by name (without parentheses), then the function is not called, but its address with meta information is simply transferred (but it may not be present, the compiler may also throw it away). doSmth(smth: sayHi) - this is passed to the function without calling it (in s / s ++, just a pointer would be passed). print(smth()) - execute the function and print its value. print(smth) print the value of the smth variable. But it does not print the address (sorry for you). - KoVadim
    • It seems I understood) Thank you! - Aleksey Timoshchenko