How to Unwrap the Elements of an Array in Swift? (Ie. Array<Int> as Array<Int>)

How to unwrap the elements of an Array in Swift? (ie. ArrayInt? as ArrayInt)

update: Xcode 7.2 • Swift 2.1.1

let arrayOfStrings = ["0", "a", "1"]
let numbersOnly = arrayOfStrings.flatMap { Int($0) }

print(numbersOnly) // [0,1]

swift convert RangeInt to [Int]

You need to create an Array<Int> using the Range<Int> rather than casting it.

let intArray: [Int] = Array(min...max)

Safe (bounds-checked) array lookup in Swift, through optional bindings?

Alex's answer has good advice and solution for the question, however, I've happened to stumble on a nicer way of implementing this functionality:

extension Collection {
/// Returns the element at the specified index if it is within bounds, otherwise nil.
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}


Example

let array = [1, 2, 3]

for index in -20...20 {
if let item = array[safe: index] {
print(item)
}
}

Returning a raw value from an Array in Swift (rather than an ArraySlice)

[1..<cycleStartsArr.count]

is an array OF rangeS.

You meant

cycleStartsArr.indices.dropFirst()

Or better yet,

import Algorithms

for (endDate, startDate) in cycleStartsArr.adjacentPairs() {

Unwrap Sparse Array in Swift

You can't do this right now in Swift. To add that function as an extension to Array, you'd have to mark somehow that it's only callable with certain kinds of arrays: those with optional values as the subtype. Unfortunately, you can't further specialize a generic type, so global functions are the only way possible.

This is the same reason Array has a sort method that takes a comparison function as a parameter, but it doesn't have a sort that "just works" if the array is full of Comparable members - to get that kind of function, you have to look at the top-level sort:

func sort<T : Comparable>(inout array: [T])

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 becomes joined, example [nil, "1", "2"].flatMap({$0}).joined()
  • joinWithSeparator becomes joined(separator:) (only available to Array of Strings)

In Swift 4

var array = ["1", "2", "3"]
array.joined(separator:"-")

How to create range in Swift?

Updated for Swift 4

Swift ranges are more complex than NSRange, and they didn't get any easier in Swift 3. If you want to try to understand the reasoning behind some of this complexity, read this and this. I'll just show you how to create them and when you might use them.

Closed Ranges: a...b

This range operator creates a Swift range which includes both element a and element b, even if b is the maximum possible value for a type (like Int.max). There are two different types of closed ranges: ClosedRange and CountableClosedRange.

1. ClosedRange

The elements of all ranges in Swift are comparable (ie, they conform to the Comparable protocol). That allows you to access the elements in the range from a collection. Here is an example:

let myRange: ClosedRange = 1...3

let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c", "d"]

However, a ClosedRange is not countable (ie, it does not conform to the Sequence protocol). That means you can't iterate over the elements with a for loop. For that you need the CountableClosedRange.

2. CountableClosedRange

This is similar to the last one except now the range can also be iterated over.

let myRange: CountableClosedRange = 1...3

let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c", "d"]

for index in myRange {
print(myArray[index])
}

Half-Open Ranges: a..<b

This range operator includes element a but not element b. Like above, there are two different types of half-open ranges: Range and CountableRange.

1. Range

As with ClosedRange, you can access the elements of a collection with a Range. Example:

let myRange: Range = 1..<3

let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c"]

Again, though, you cannot iterate over a Range because it is only comparable, not stridable.

2. CountableRange

A CountableRange allows iteration.

let myRange: CountableRange = 1..<3

let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c"]

for index in myRange {
print(myArray[index])
}

NSRange

You can (must) still use NSRange at times in Swift (when making attributed strings, for example), so it is helpful to know how to make one.

let myNSRange = NSRange(location: 3, length: 2)

Note that this is location and length, not start index and end index. The example here is similar in meaning to the Swift range 3..<5. However, since the types are different, they are not interchangeable.

Ranges with Strings

The ... and ..< range operators are a shorthand way of creating ranges. For example:

let myRange = 1..<3

The long hand way to create the same range would be

let myRange = CountableRange<Int>(uncheckedBounds: (lower: 1, upper: 3)) // 1..<3

You can see that the index type here is Int. That doesn't work for String, though, because Strings are made of Characters and not all characters are the same size. (Read this for more info.) An emoji like , for example, takes more space than the letter "b".

Problem with NSRange

Try experimenting with NSRange and an NSString with emoji and you'll see what I mean. Headache.

let myNSRange = NSRange(location: 1, length: 3)

let myNSString: NSString = "abcde"
myNSString.substring(with: myNSRange) // "bcd"

let myNSString2: NSString = "acde"
myNSString2.substring(with: myNSRange) // "c" Where is the "d"!?

The smiley face takes two UTF-16 code units to store, so it gives the unexpected result of not including the "d".

Swift Solution

Because of this, with Swift Strings you use Range<String.Index>, not Range<Int>. The String Index is calculated based on a particular string so that it knows if there are any emoji or extended grapheme clusters.

Example

var myString = "abcde"
let start = myString.index(myString.startIndex, offsetBy: 1)
let end = myString.index(myString.startIndex, offsetBy: 4)
let myRange = start..<end
myString[myRange] // "bcd"

myString = "acde"
let start2 = myString.index(myString.startIndex, offsetBy: 1)
let end2 = myString.index(myString.startIndex, offsetBy: 4)
let myRange2 = start2..<end2
myString[myRange2] // "cd"

One-sided Ranges: a... and ...b and ..<b

In Swift 4 things were simplified a bit. Whenever the starting or ending point of a range can be inferred, you can leave it off.

Int

You can use one-sided integer ranges to iterate over collections. Here are some examples from the documentation.

// iterate from index 2 to the end of the array
for name in names[2...] {
print(name)
}

// iterate from the beginning of the array to index 2
for name in names[...2] {
print(name)
}

// iterate from the beginning of the array up to but not including index 2
for name in names[..<2] {
print(name)
}

// the range from negative infinity to 5. You can't iterate forward
// over this because the starting point in unknown.
let range = ...5
range.contains(7) // false
range.contains(4) // true
range.contains(-1) // true

// You can iterate over this but it will be an infinate loop
// so you have to break out at some point.
let range = 5...

String

This also works with String ranges. If you are making a range with str.startIndex or str.endIndex at one end, you can leave it off. The compiler will infer it.

Given

var str = "Hello, playground"
let index = str.index(str.startIndex, offsetBy: 5)

let myRange = ..<index // Hello

You can go from the index to str.endIndex by using ...

var str = "Hello, playground"
let index = str.index(str.endIndex, offsetBy: -10)
let myRange = index... // playground

See also:

  • How does String.Index work in Swift
  • How does String substring work in Swift

Notes

  • You can't use a range you created with one string on a different string.
  • As you can see, String ranges are a pain in Swift, but they do make it possibly to deal better with emoji and other Unicode scalars.

Further Study

  • String Range examples
  • Range Operator documentation
  • Strings and Characters documentation

What's the difference between [Int] & ArrayInt?

From The Swift Programming Language: Collection Types

Array Type Shorthand Syntax

The type of a Swift array is written in full as Array<SomeType>, where SomeType is the type of values the array is allowed to store. You can also write the type of an array in shorthand form as [SomeType]. Although the two forms are functionally identical, - the shorthand form is preferred and is used throughout this guide when referring to the type of an array.

That is, both comments are correct - and both represent the same type.



Related Topics



Leave a reply



Submit