Swift 3: Convert a String to an Array

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 a SequenceType, and
  • String conforms to the SequenceType 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 to
SequenceType, 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 its
Characters:

let string = "Hello br>let characters = Array(string)
print(characters)
// ["H", "e", "l", "l", "o", " ", ", ", " ", "]

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.

String into array in Swift 3

Swift 4

You can use Decodable:

let str = "[173.0, 180.5],[173.0, 180.0],[174.0, 180.5],[174.0, 183.0]"
let json = "[\(str)]".data(using: .utf8)!

let numbers = try JSONDecoder().decode([[Double]].self, from: json).flatMap { $0 }
let result = stride(from: 0, to: numbers.count, by: 4).map { startIndex -> [Double] in
let endIndex = min(startIndex + 4, numbers.count)
return Array(numbers[startIndex..<endIndex])
}

Swift 3

One option is to use the old-school NSScanner to extract the numbers from the string to a flat array, then build a 2 dimensional array off that:

let str = "[173.0, 180.5],[173.0, 180.0],[174.0, 180.5],[174.0, 183.0]"
let scanner = Scanner(string: str)
scanner.charactersToBeSkipped = CharacterSet(charactersIn: "[], ")

// Build the flat array
var numbers = [Double]()
while !scanner.isAtEnd {
var d = 0.0
if scanner.scanDouble(&d) {
numbers.append(d)
}
}

// Now the 2 dimensional array
let result = stride(from: 0, to: numbers.count, by: 4).map { startIndex -> [Double] in
let endIndex = min(startIndex + 4, numbers.count)
return Array(numbers[startIndex..<endIndex])
}

Convert String to Array of Integers in Swift 3?

The question is: if you want to save an array of Int why do write and read a String?

The easiest way to save an array of Int is the property list format.

Although the recommended way in Swift is the PropertyListSerialization class this writes and reads an array of Int by bridging the Swift Array to NSArray.

let file = "sample.plist"
let arrayToWrite = [Int](1...100)
var arrayToRead = [Int]()

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

let url = dir.appendingPathComponent(file)

// writing

(arrayToWrite as NSArray).write(to: url, atomically: false)

//reading

arrayToRead = NSArray(contentsOf: url) as! [Int]
print(arrayToRead)
}

The swiftier way using PropertyListSerialization is

// writing

do {
let data = try PropertyListSerialization.data(fromPropertyList: arrayToWrite, format: .binary, options: 0)
try data.write(to: url, options: .atomic)
}
catch { print(error) }

//reading

do {
let data = try Data(contentsOf: url)
arrayToRead = try PropertyListSerialization.propertyList(from: data, format: nil) as! [Int]

print(arrayToRead)
}
catch { print(error) }

Parse String containing Array of String into Array using Swift 3.0

it's a JSON String, you have to convert it in normal string array by using JSONSerialization.

Swift 3.0

func convertToArray(str: String) -> [String]? {

let data = str.data(using: .utf8)

do {
return try JSONSerialization.jsonObject(with: data!, options: []) as? [String]
} catch {
print(error.localizedDescription)
}

return nil

}

let aString: String = "[\"One\", \"Two\", \"Three\", \"Four\"]"

let arrayString = convertToArray(str: aString)

print(arrayString) // ["One", "Two", "Three", "Four"]

Swift Convert A String-As-An-Array, To An Array Of Strings

Encode your "string array" to data, then decode this data as JSON to a Swift Array.

Like this, for example:

let source = "[\"word1\",\"word2\"]"

guard let data = source.dataUsingEncoding(NSUTF8StringEncoding),
arrayOfStrings = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String] else {
fatalError()
}

print(arrayOfStrings) // ["word1", "word2"]
print(arrayOfStrings[1]) // "word2"

Convert string into array without quotation marks in Swift 3

You can apply a flatMap call on the [String] array resulting from the call to components(separatedBy:), applying the failable init(_:radix:) of Int in the body of the transform closure of the flatMap invokation:

let strNumbers = "1 2 3 4"
let numbersArray = strNumbers
.components(separatedBy: " ")
.flatMap { Int($0) }

print(numbersArray) // [1, 2, 3, 4]
print(type(of: numbersArray)) // Array<Int>


Related Topics



Leave a reply



Submit