Eric Eric - 17 days ago 8
Swift Question

Return a boolean value from a function in Swift 3.0

I cannot figure how the new first label proposal for Swift 3.0 applies to returnTypes with Bool:

var firstString = "string"
var secondString = "thing"

func areTheStringsAnagrams(first: String, second: String) -> Bool {
return first.characters.sorted() == second.characters.sorted()
}

areTheStringsAnagrams(first: firstString, second: secondString)


Why is the call to the function unused?

The error is:

/swift-execution/Sources/main.swift:11:1: warning: result of call to 'areTheStringsAnagrams(first:second:)' is unused
areTheStringsAnagrams(first: firstString, second: secondString)
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Although a previous questions focused on
NSLayoutConstraints
(i.e., Result of call to [myFunction] is unused) in a comparison to Objective-C, the present question is narrower in that it focuses exclusively on function calls with a
returnType
of
Bool
in Swift 3.0.

Answer

You aren't doing anything with the result.

You can assign the result:

let anagrams = areTheStringsAnagrams(first: firstString, second: secondString)

If you don't need the result, you have two options. You can either assign to _

_ = areTheStringsAnagrams(first: firstString, second: secondString)

or you could mark the function with @discardableResult

@discardableResult
func areTheStringsAnagrams(first: String, second: String) -> Bool {
    return first.characters.sorted() == second.characters.sorted()
}

In this case, I wouldn't do the last option since if you ignore the result, what was the point of calling it?

Comments