Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Beginning Swift

You're reading from   Beginning Swift Master the fundamentals of programming in Swift 4

Arrow left icon
Product type Paperback
Published in May 2018
Publisher Packt
ISBN-13 9781789534313
Length 202 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Rob Kerr Rob Kerr
Author Profile Icon Rob Kerr
Rob Kerr
Kåre Morstøl Kåre Morstøl
Author Profile Icon Kåre Morstøl
Kåre Morstøl
Arrow right icon
View More author details
Toc

Substring


SubString is for strings what ArraySlice is for arrays: a view of a part of a string, where its startIndex and endIndex are indices into the original string. It conforms to the same protocols as String:

StringProtocol contains many of the common text operations, so when you write functions that take a string parameter you can often use StringProtocol instead to also accept substrings. When you do, you have to use generics, as shown here:

func foo<S: StringProtocol>(s: S) {
  // use 's' almost like a normal string.
}

Just as with ArraySlice, substrings keep a reference to the entire string, so when you are done processing substrings you should turn them into normal strings and allow the original string to be released (if nothing else is using it):

String(substring)

Creating Substrings

Substrings can be created in many different ways:

  • We can create substrings by passing a range of indices to a string subscript:

    string[from..<upTo]
    string[from...upToAndIncluding...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image