3 ms·
the main problem with swift strings is actually naming. You don't have simple method replace(src:String, dst:String) but you have weird stringByReplacingOccu
by ex3ndr 11y ago
the main problem with swift strings is actually naming. You don't have simple method
replace(src:String, dst:String)
but you have weird
stringByReplacingOccurrencesOfString(src, withString: dest, options: NSStringCompareOptions(), range: nil)
Why not to have simple convenience method?
- cballard 11y agoThat is not a Swift method, it's an Objective-C method on NSString, which Swift String can be silently converted to.
- zw 11y agoNot anymore; those methods are implemented in an extension on `String` that don't always involve bridging back.
- mikeash 11y agoThey're still only available if you import Foundation. They're just NSString methods with wrappers. The real problem is just that Swift itself doesn't have methods for locating a string in another string, or replacing strings in another string. This is why I was careful to say that Swift's API is the best in terms of its fundamental design. It still has a lot of missing functionality compared to other languages right now.
- alexbock 11y agoAside from the fact that they carried that style of naming over from Objective-C, the one benefit I see is that it makes it obvious that it returns the result in a new string rather than modifying the object itself. In C++ you would need to look at the signature to tell which way a method named replace worked, e.g. void A::replace(const A& source, const A& dest); vs A A::replace(const A& source, const A& dest) const; That said, I think you can get this same benefit without such a verbose name. Perhaps something like "withReplacement"?
- cballard 11y agoA solution to this would be to disallow mutable value types. Then, all methods would _have_ to return a new instance. The compiler implementation could use mutability behind the scenes for efficiency, while the language exclusively allowed immutable values.
- hockeybias 11y agoLovely. Remember Microsoft s*cks.