OT: Swift is now open source

Michel Fortin via Digitalmars-d digitalmars-d at puremagic.com
Sun Dec 6 05:45:57 PST 2015


On 2015-12-06 10:43:24 +0000, Jacob Carlborg <doob at me.com> said:

>> You're decoding characters (grapheme clusters) as you advance those indexes.
> 
> Not really what I needed, for me it would be enough with slicing the bytes.

That only works if the actual underlying representation is UTF8 (or 
other single-byte encoding). String abstracts that away from you. But 
you can do this if you want to work with bytes:

	let utf8View = str.utf8
	utf8View[utf8View.startIndex.advancedBy(2) ..< 
utf8View.endIndex.advancedBy(-1)]

or:

	let arrayOfBytes = Array(str.utf8)
	arrayOfBytes[2 ..< arrayOfBytes.count-1]


>> It's called indexOf. (Remember, the index type is an iterator.) It does
>> return an optional. It will work for any type conforming to the
>> ContainerType protocol where Element conforms to Equatable. Like this:
>> 
>>      let str = "Hello, playground"
>>      let start = str.unicodeScalars.indexOf("p")!
>>      let end = str.unicodeScalars.indexOf("g")!
>>      str.unicodeScalars[start ..< end] // "play"
>>      str.unicodeScalars[start ... end] // "playg"
> 
> I was looking for a method to return the first element matching a predicate.

	container.indexOf(predicate)
	container.indexOf { (element) in element == "p" }
	container.indexOf { $0 == "p" }

> If it's an iterator I would expect to be able to get the value it 
> points to. I can't see how I can do that with an Index in Swift.

	container[index]

The index is an iterator in the sense that it points at one location in 
the container and apply some container-released logic as you advance. 
But you still have to use the container to access its value. The index 
does not expose the value even when it knows about it internally.

Not all index types are like that. Containers with random access 
normally use Int as their index type because it's sufficient and 
practical.


-- 
Michel Fortin
michel.fortin at michelf.ca
http://michelf.ca



More information about the Digitalmars-d mailing list