How to copy end of the Array in swift?
And another one ...
let array = [1, 2, 3, 4, 5]
let fromIndex = 2
let endOfArray = array.dropFirst(fromIndex)
print(endOfArray) // [3, 4, 5]
This gives an ArraySlice
which should be good enough for most
purposes. If you need a real Array
, use
let endOfArray = Array(array.dropFirst(fromIndex))
An empty array/slice is created if the start index is larger than (or equal to) the element count.
In Swift, what's the cleanest way to get the last two items in an Array?
With Swift 5, according to your needs, you may choose one of the following patterns in order to get a new array from the last two elements of an array.
#1. Using Array's suffix(_:)
With Swift, objects that conform to Collection
protocol have a suffix(_:)
method. Array's suffix(_:)
has the following declaration:
func suffix(_ maxLength: Int) -> ArraySlice<Element>
Returns a subsequence, up to the given maximum length, containing the final elements of the collection.
Usage:
let array = [1, 2, 3, 4]
let arraySlice = array.suffix(2)
let newArray = Array(arraySlice)
print(newArray) // prints: [3, 4]
#2. Using Array
's subscript(_:)
As an alternative to suffix(_:)
method, you may use Array
's subscript(_:)
subscript:
let array = [1, 2, 3, 4]
let range = array.index(array.endIndex, offsetBy: -2) ..< array.endIndex
//let range = array.index(array.endIndex, offsetBy: -2)... // also works
let arraySlice = array[range]
let newArray = Array(arraySlice)
print(newArray) // prints: [3, 4]
how to make a deep copy of a swift array of class objects
As a simple statement, you could use code like this:
var copiedArray = array.map{$0.copy()}
Note that the term "deepCopy" is a little misleading for what you're talking about. What if the array is heterogeneous and contains other containers like arrays, dictionaries, sets, and other custom container and "leaf" objects? What you should really do is to create a protocol DeepCopiable and make it a requirement that any object that conforms to DeepCopiable require that any child objects also conform to the DeepCopiable protocol, and write the deepCopy() method to recursively call deepCopy() on all child objects. That way you wind up with a deep copy that works at any arbitrary depth.
How do I fetch the last element of an array in Swift?
Update: Swift 2.0 now includes first:T?
and last:T?
properties built-in.
When you need to you can make the built-in Swift API's prettier by providing your own extensions, e.g:
extension Array {
var last: T {
return self[self.endIndex - 1]
}
}
This lets you now access the last element on any array with:
[1,5,7,9,22].last
Move some objects of array at the end in swift 3
Your approach is far too complicated. You have two sorting criteria:
isIncluded
–true
values should be sorted beforefalse
values,lastupdatedTime
– larger values should be sorted first.
That can be done with a single sort()
call:
conversationList.sort(by: {
if $0.isIncluded != $1.isIncluded {
return $0.isIncluded
} else {
return $0.lastupdatedTime > $1.lastupdatedTime
}
})
This assumes isIncluded
is a boolean variable (which would be sensible). If it is an integer (as you indicated in the comments)
then it is even simpler: (compare Swift - Sort array of objects with multiple criteria):
conversationList.sort(by: {
($0.isIncluded, $0.lastupdatedTime) > ($1.isIncluded, $1.lastupdatedTime)
})
How can I perform an Array Slice in Swift?
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
Related Topics
Swift Random Float Between 0 and 1
How to Unwrap Double Optionals
Instance Member Cannot Be Used on Type
How to Convert a View (Not Uiview) to an Image
How to Create Array of Unique Object List in Swift
Nsuserdefaults Not Working on Xcode Beta With Watch Os2
Binary Operator * Cannot Be Applied to Operands of Type Int and Double
Check Password String Strength Criteria in Swift
Choosing Coredata Entities from Form Picker
How to Resolve "Ambiguous Use Of" Compile Error With Swift #Selector Syntax
Nsdate() or Date() Shows the Wrong Time
How to Set Associated Objects in Swift
Getting a "This Application Is Modifying the Autolayout Engine from a Background Thread" Error