[swift-users] overloading methods where only difference is optional vs. non-optional type
Phil Kirby
phil.kirby at gmail.com
Tue Oct 10 05:51:52 CDT 2017
2 down vote favorite
Original StackOverflow post:
https://stackoverflow.com/questions/46620311/overloading-methods-where-only-difference-is-optional-vs-non-optional-type
I was under the impression that swift can have overloaded methods that differ only in the type of object that the methods return. I would think that I could have two funcs with the same signature yet they differ in return type.
import Foundation
// ambiguous use of 'IsTextEmpty(text:)'
func IsTextEmpty(text : String?) -> Bool? {
return text?.isEmpty
}
func IsTextEmpty(text : String?) -> Bool {
guard let text = text else {
return true
}
return text.isEmpty
}
let text: String? = nil
if let empty = IsTextEmpty(text:"text") {
print("Not Empty")
}
if IsTextEmpty(text: text) {
print("Empty")
}
Here, both functions have the same input parameters but one func returns an optional Bool? and the other returns a Bool. In this case I get an error:
ambiguous use of 'IsTextEmpty(text:)'
If I change the name of one of the input parameters I no longer get the ambiguous error:
// Works
func IsTextEmpty(foo : String?) -> Bool? {
return foo?.isEmpty
}
func IsTextEmpty(text : String?) -> Bool {
guard let text = text else {
return true
}
return text.isEmpty
}
let text: String? = nil
if let empty = IsTextEmpty(foo:"text") {
print("Not Empty")
}
if IsTextEmpty(text: text) {
print("Empty")
}
Shouldn't the compiler detect that they are two distinct methods even though their return types are different, since an optional Bool? is a different type from a non-optional Bool?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171010/8e78f818/attachment.html>
More information about the swift-users
mailing list