Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

split
swift
communitycreator

Split a string to characters with split(separator:) in Swift

Theodore Kelechukwu Onyejiaku

Overview

The split(separator:) method returns the longest possible sub-sequences of a collection. In this case, we want to use this method to split a string into an array of characters.

Syntax

This is the syntax for the split(separator:) method:

string.split(separator: separatorElement)

Parameters

separatorElement: This is the element that should be split upon.

Return value

The split method returns smaller sub-parts of the array that are obtained from the subject string.

Code example

// create some strings
let numbers = "1 2 3 4"
let alphabets = "a-b-c-d"

// split strings into characters
let numberCharacters = numbers.split(separator: " ")
let alphabetCharacters = alphabets.split(separator: "-")

// print results
print(numberCharacters)
print(alphabetCharacters)
Split a string into an array of characters

Code explanation

  • Lines 2–3: We create two strings, numbers and strings.
  • Lines 6–7: We split the strings into characters.
  • Lines 10–11: We print the results to the console.

RELATED TAGS

split
swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring