[swift-users] Overload by return type optionality?
Rick Mann
rmann at latencyzero.com
Thu Oct 13 17:31:30 CDT 2016
> On Oct 13, 2016, at 14:51 , Greg Parker <gparker at apple.com> wrote:
>
>>
>> On Oct 13, 2016, at 2:36 PM, Rick Mann via swift-users <swift-users at swift.org> wrote:
>>
>> It seems I can write this:
>>
>> extension String
>> {
>> public func deleting(prefix inPrefix: String) -> String
>> public func deleting(prefix inPrefix: String) -> String?
>> }
>>
>> But I was hoping it would do the right thing:
>>
>> let a = s.deleting(prefix: "foo")
>> if let b = s.deleting(prefix: "foo") { }
>>
>> But it finds these ambiguous, and I'm not sure how to specify which I want.
>
> You can specify which you want by explicitly naming the type:
> let a = s.deleting(prefix: "foo") as String
> or
> let a : String = s.deleting(prefix: "foo")
>
> …but presumably that doesn't give you the usability that you were hoping for.
Eh, it's close, especially if Joe Groff is right that the if-let case shouldn't be ambiguous.
A better question would be to ask, is this a reasonable approach, to overload a method like this for this kind of behavior. There are two ways to think about stripping the prefix off a string: a string minus a non-existent prefix is just the string, or you want to know that the prefix didn't exist. This gives you both, but might make for subtly unexpected behavior.
Would it make sense to be able to specify priority for a set of overloaded methods to help resolve ambiguity?
--
Rick Mann
rmann at latencyzero.com
More information about the swift-users
mailing list