[swift-users] the pain of strings

Charles Srstka cocoadev at charlessoft.com
Fri Jun 30 20:31:45 CDT 2017


> On Jun 30, 2017, at 4:44 PM, David Baraff via swift-users <swift-users at swift.org> wrote:
> 
> I know, I’ve read tons about about this.  I sympathize.  Unicode, it’s all very complex.
> 
> But.
> 
>  BUT.
> 
> Python:
>  shortID = longerDeviceID[-2:]		# give me the last two characters
> 
> Swift:
>  let shortID = String(longerDeviceID.characters.dropFirst(longerDeviceID.characters.count - 2))
> 
> I can’t even read the above without my eyes glazing over.  As has been pointed out, an API which demands this much verbosity is crippling for many developers, to say the least.
> 
> With Swift 4, am I correct that it will be at least:
> 
>  let shortID = String(longerDeviceID.dropFirst(longerDeviceID.count - 2))

Hey, look on the bright side. They could have done what they’ve done with Data; make it *look* like simple integer subscripts will work, when actually they will blow up in your face at runtime.

func parseSome(data: Data) {
	let magic = data[0..<4]
}

That’ll read the first four bytes of ‘data’ into ‘magic’, right? Well, not if someone does this when calling the function:

func parseSome(data: inputData[someStart..<someEnd])

Now the ‘data’ your function has received is actually a slice, and when it tries to access index 0, it’ll actually access the first byte of the original data the slice was made from, *not* the first byte of the slice! On the currently available version of Xcode, that’ll read the wrong data; with the current sources from the trunk, it’ll crash. Either way, you won’t know until runtime.

Charles

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170630/1244a3e4/attachment.html>


More information about the swift-users mailing list