Function as a parameter in another function

Hey. I hope my favorite community is doing well.
The title speaks for itself.
Task: To use a function as a parameter in another function.
Specification: The function must measure time of execution.
Frameworks: Foundation, SwiftUI
Note: Function mostCommonName ( by name I meant element ), works properly on its own.

var someArray = ["cat","dog","mouse","goose","deer","cat","cat","dog"]

print(mostCommonName(array: someArray))

func runningTime (title: String, operationBloc: () -> ()){

let start = CFAbsoluteTimeGetCurrent()


let finish = CFAbsoluteTimeGetCurrent()

let time = finish - start

print("Function: \(title) has been executed in \(time) seconds")


runningTime(title: "Merge") {

mostCommonName(array: someArray)


I feel like the error is minor, perhaps the problem is in my syntax.
I would tremendously appreciate your help. Thank you in advance!!!

operationBloc() // you forgot to execute the closure

Did you also meant to write block instead of bloc?

1 Like

You want to write operationBloc() instead of operationBloc inside runningTime to actually call the closure. Also, the warning just means that your function mostCommonName(array:) returns something, but you haven't assigned anything to the return value. You can either put an underline in front of it like this: _ = mostCommonName(array: someArray), or you can annotate the mostCommonName(array:) function like this:

func mostCommonName(array: [String]) -> String { ... }

With this annotation, the compiler won't complain anymore if you don't use the result of the function. It's used in many functions in the standard library, especially on the Set type.

1 Like

Yeah, exactly. That was a typo, I guess. "block" is a proper word. I also didn't mean to use "merge".

Thanks it helped. I guess that I overworked today. That was a stupid mistake.

1 Like
Terms of Service

Privacy Policy

Cookie Policy