In Swift, Array [String] Slicing Return Type Doesn't Seem to Be [String]

In Swift, Array [String] slicing return type doesn't seem to be [String]

Subscripting an array with a range doesn't return an array, but a slice. You can create an array out of that slice though.

var tags = ["this", "is", "cool"]
tags[1..<3]
var someTags: Slice = tags[1..<3]
var someTagsArray: [String] = Array(someTags)

How to convert Swift.ArraySlice to Swift.Array?

The actual reason of the error is in this line

lastExp["ArgList"] = (lastExp["ArgList"] as! [String]).dropLast()

You are re-assigning the type ArraySlice rather then intended Array so already there you have to create a new array

lastExp["ArgList"] = Array((lastExp["ArgList"] as! [String]).dropLast())

And never ever check strings and collection types for emptiness with .count == 0. There is an optimized isEmpty property and don't wrap an if expression in parentheses in Swift:

if !lastExp.isEmpty { ...

ArraySlice in Array Swift

Just initialize a new Array with the slice:

let arr1 = [0,1,2,3,4,5,6,7]
let slice = arr1[2...5]
let arr2 = Array(slice)

Cannot assign value of type 'ArraySlice User ' to type '[User]'

You need to convert the array slices returned by prefix and suffix to arrays by calling the initializer of Array accepting an ArraySlice.

let data = serverResponse.data as! [User]
collectionData = Array(data.prefix(upTo: 10))
tableData = Array(data.suffix(from: 11))

Try to get sub array With given Range

let currentData = [Info(), Info(), Info()]
let subarr0 = currentData[0..<2] // ArraySlice
let subarr1 = Array(currentData[0..<2]) // 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", " ", ", ", " ", "]

Get First 10 Objects from Array

You need to turn your ArraySlice into an Array.

tenLat = Array(latitudeArray.prefix(10))



Related Topics



Leave a reply



Submit