[swift-users] String manipulation (replacingOccurrences) in Linux swift
Brent Royal-Gordon
brent at architechies.com
Thu May 26 16:29:38 CDT 2016
> #if os(Linux)
> print("Let's change those carriage returns...")
> processedString = string.replacingOccurrences(of: "\r\n", with: "\n")
> #else
> processedString = string.replacingOccurrences(of: "\r\n", with: "\n")
> #endif
> And it compiles flawlessly in linux, but when it’s time to execute, it throws an error message like:
> Let's change those carriage returns...
> Illegal instruction (core dumped)
I don't have a Swift on Linux box, so I can't really run Corelibs Foundation myself. But looking at the source code <https://github.com/apple/swift-corelibs-foundation/blob/182d5c970114ec7f981aceaaa054d51e29923cf3/Foundation/NSString.swift#L1383>, I'm not sure that it will behave correctly when you replace a string with a differently-sized string and .backwardsSearch is not set. Maybe there's something I'm missing, but it looks to me like each replacement will shift the characters in the string, but the ranges won't move with them. The replacements will miss their targets more and more, and eventually—if the replacement is shorter than the original and one of the matches is near enough to the end—they might run past the end of the string.
Carlos: Try passing `options: .backwardsSearch` to `replacingOccurrences`. If I'm right about this being a bug, doing that should work around it, and you ought not to notice any difference in your code's behavior. (This is not something you should have necessarily figured out yourself; you haven't missed anything obvious.)
swift-corelibs-dev (who I've cc'd on this thread): Am I correct that this is a bug? Should it be/has it been filed? (A quick-and-dirty search of the bug tracker seems to indicate it hasn't been, but I don't have that much experience with it.)
--
Brent Royal-Gordon
Architechies
More information about the swift-users
mailing list