Code
Code

Reputation: 6251

String: substringToIndex for unicode scalars

To get the first 50 characters of a String, I can do

s.substringToIndex(s.startIndex.advancedBy(50)))

How can I get the first 50 unicode scalars of a String?

I can get a String.UnicodeScalarView object using s.unicodeScalars but I don't know how to go from there.

Upvotes: 1

Views: 103

Answers (1)

Martin R
Martin R

Reputation: 539845

s.unicodeScalars returns a String.UnicodeScalarView which conforms to CollectionType. You can get a subsequence of the collection with

u = s.unicodeScalars
u[u.startIndex ..< u.startIndex.advancedBy(50)]

or, in the case of an initial sequence, more simply with

u.prefix(50)

There is a small difference: Subscripting requires that the specified subrange exists, and will terminate with a runtime exception otherwise. prefix() truncates at the given index, i.e. it returns a subsequence with 50 or less elements.

Upvotes: 1

Related Questions