Convert Swift string to array
It is even easier in Swift:
let string : String = "Hello br>let characters = Array(string)
println(characters)
// [H, e, l, l, o, , , , , ]
This uses the facts that
- an
Array
can be created from aSequenceType
, and String
conforms to theSequenceType
protocol, and its sequence generator
enumerates the characters.
And since Swift strings have full support for Unicode, this works even with characters
outside of the "Basic Multilingual Plane" (such as ) and with extended grapheme
clusters (such as , which is actually composed of two Unicode scalars).
Update: As of Swift 2, String
does no longer conform toSequenceType
, but the characters
property provides a sequence of the
Unicode characters:
let string = "Hello br>let characters = Array(string.characters)
print(characters)
This works in Swift 3 as well.
Update: As of Swift 4, String
is (again) a collection of itsCharacter
s:
let string = "Hello br>let characters = Array(string)
print(characters)
// ["H", "e", "l", "l", "o", " ", ", ", " ", "]
How do I convert a Swift Array to a String?
If the array contains strings, you can use the String
's join
method:
var array = ["1", "2", "3"]
let stringRepresentation = "-".join(array) // "1-2-3"
In Swift 2:
var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"
This can be useful if you want to use a specific separator (hypen, blank, comma, etc).
Otherwise you can simply use the description
property, which returns a string representation of the array:
let stringRepresentation = [1, 2, 3].description // "[1, 2, 3]"
Hint: any object implementing the Printable
protocol has a description
property. If you adopt that protocol in your own classes/structs, you make them print friendly as well
In Swift 3
join
becomesjoined
, example[nil, "1", "2"].flatMap({$0}).joined()
joinWithSeparator
becomesjoined(separator:)
(only available to Array of Strings)
In Swift 4
var array = ["1", "2", "3"]
array.joined(separator:"-")
Split a String into an array in Swift?
The Swift way is to use the global split
function, like so:
var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
with Swift 2
In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. This means that String no longer adopts the SequenceType or CollectionType protocols and you must instead use the .characters
property to access a CharacterView type representation of a String instance. (Note: CharacterView does adopt SequenceType and CollectionType protocols).
let fullName = "First Last"
let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)
// or simply:
// let fullNameArr = fullName.characters.split{" "}.map(String.init)
fullNameArr[0] // First
fullNameArr[1] // Last
Swift string to array of single character strings
You can do it like as follows... Initialize a new string inside the map.
let test = "thisIsATest"
let array = test.map( { String($0) })
How to convert String Array to String in Swift
This should work.
let string = ["1","2","3","4","5"]
let newString = "\"[\"" + string.joined(separator: "\",\"") + "\"]\""
print(newString) // Prints "["1","2","3","4","5"]"
Edit: The best way is to use @vadian's answer. Albeit, this doesn't seem like a valid use case.
Swift 3 : Convert a String to an Array
Instead of splitting the character-view, you can use the simple components(separatedBy:)
API.
Here's a sample that would look better and work:
if let toLearn = word?.text,
let recorded = result?.bestTranscription.formattedString {
let wordsToLearn = toLearn.components(separatedBy: " ")
let recordedWords = recorded.components(separatedBy: " ")
}
Note: nonoptionals are better than forced unwraps and optionals.
Related Topics
Autoresizing Masks Programmatically VS Interface Builder/Xib/Nib
How to Get My Ip Address Programmatically on Ios/Macos
Load Resources from Relative Path Using Local HTML in Uiwebview
How to Change Navigation Bar Color in iOS 7
Best Practices For Storyboard Login Screen, Handling Clearing of Data Upon Logout
Request Failed: Unacceptable Content-Type: Text/Html Using Afnetworking 2.0
Move Textfield Up When the Keyboard Has Appeared in Swiftui
Core Data: Quickest Way to Delete All Instances of an Entity
How to Change Image Tintcolor in iOS and Watchkit
How to Show "Done" Button on iOS Number Pad Keyboard
Uiwebview Open Links in Safari
How to Play Video With Avplayerviewcontroller (Avkit) in Swift
Ios: Convert Utc Nsdate to Local Timezone
Prevent Screen Capture in an iOS App
Image Resolution For New Iphone 6 and 6+, @3X Support Added
How to Hide Google Maps Location Dot
Getting and Setting Cursor Position of Uitextfield and Uitextview in Swift