[swift-evolution] NSString.contains(_:) returns false for empty string argument

Ole Begemann ole at oleb.net
Mon Sep 5 13:23:59 CDT 2016


Six weeks ago there was a discussion [1] (and a subsequent fix [2]) about the behavior of `String.hasPrefix(_:)` and `String.hasSuffix(_:)` with empty string arguments. After the fix, `str.hasPrefix("")` always returns `true`.

This leads to inconsistent behavior with the `NSString.contains(_:)` method, which returns `false` for an empty string argument:

    let str = "Hello"
    str.contains("") // returns false

If `contains` were part of the stdlib like `hasPrefix` and `hasSuffix` are, I would consider this a bug. But `contains` comes from Foundation and I'm not sure how that changes things. Would it make sense to add a variant of `contains(_:)` to the stdlib and fix the behavior there?

I'm assuming it's too late for Swift 3 and it will be fixed with the String remodeling in Swift 4 anyway, but I just noticed this and I thought I'd ask.

Ole

[1]: https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160718/024630.html
[2]: https://bugs.swift.org/browse/SR-2131



More information about the swift-evolution mailing list