var mentions = ["@alex", "@jason", "@jessica", "@john"]
I want to limit my array to 3 items, so I want to splice it:
var slice = [String]() if mentions.count > 3 { slice = mentions[0...3] //alex, jason, jessica } else { slice = mentions }
However, I'm getting:
Ambiguous subscript with base type '[String]' and index type 'Range'
Apple Swift version 2.2 (swiftlang-703.0.18.8 clang-703.0.31) Target: x86_64-apple-macosx10.9
JavaScript Array slice()The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.
In Swift, a slice is a special kind of collection that doesn't actually store any elements of its own, but rather acts as a proxy (or view) to enable us access and work with a subset of another collection as a separate instance.
Common examples of array slicing are extracting a substring from a string of characters, the "ell" in "hello", extracting a row or column from a two-dimensional array, or extracting a vector from a matrix. Depending on the programming language, an array slice can be made out of non-consecutive elements.
To filter an array in Swift: Call the Array. filter() method on an array. Pass a filtering function as an argument to the method.
The problem is that mentions[0...3]
returns an ArraySlice<String>
, not an Array<String>
. Therefore you could first use the Array(_:)
initialiser in order to convert the slice into an array:
let first3Elements : [String] // An Array of up to the first 3 elements. if mentions.count >= 3 { first3Elements = Array(mentions[0 ..< 3]) } else { first3Elements = mentions }
Or if you want to use an ArraySlice
(they are useful for intermediate computations, as they present a 'view' onto the original array, but are not designed for long term storage), you could subscript mentions
with the full range of indices in your else
:
let slice : ArraySlice<String> // An ArraySlice of up to the first 3 elements if mentions.count >= 3 { slice = mentions[0 ..< 3] } else { slice = mentions[mentions.indices] // in Swift 4: slice = mentions[...] }
Although the simplest solution by far would be just to use the prefix(_:)
method, which will return an ArraySlice
of the first n elements, or a slice of the entire array if n exceeds the array count:
let slice = mentions.prefix(3) // ArraySlice of up to the first 3 elements
We can do like this,
let arr = [10,20,30,40,50] let slicedArray = arr[1...3]
if you want to convert sliced array to normal array,
let arrayOfInts = Array(slicedArray)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With