How to know if a number is odd or even in Swift? - ios

I have an array of numbers typed Int.
I want to loop through this array and determine if each number is odd or even.
How can I determine if a number is odd or even in Swift?

var myArray = [23, 54, 51, 98, 54, 23, 32];
for myInt: Int in myArray{
if myInt % 2 == 0 {
println("\(myInt) is even number")
} else {
println("\(myInt) is odd number")
}
}

Use the % Remainder Operator (aka the Modulo Operator) to check if a number is even:
if yourNumber % 2 == 0 {
// Even Number
} else {
// Odd Number
}
or, use remainder(dividingBy:) to make the same check:
if yourNumber.remainder(dividingBy: 2) == 0 {
// Even Number
} else {
// Odd Number
}

Swift 5 adds the function isMultiple(of:) to the BinaryInteger protocol.
let even = binaryInteger.isMultiple(of: 2)
let odd = !binaryInteger.isMultiple(of: 2)
This function can be used in place of % for odd/even checks.
This function was added via the Swift Evolution process:
Preliminary Discussion in Swift Forum
Swift Evolution Proposal
Accepted Swift Evolution Implementation
Notably, isEven and isOdd were proposed but not accepted in the same review:
Given the addition of isMultiple(of:), the Core Team feels that isEven and isOdd offer no substantial advantages over isMultiple(of: 2).
Therefore, the proposal is accepted with modifications. isMultiple(of:) is accepted but isEven and isOdd are rejected.
If desired, those methods can be added easily through extension:
extension BinaryInteger {
var isEven: Bool { isMultiple(of: 2) }
var isOdd: Bool { !isEven }
}

"Parity" is the name for the mathematical concept of Odd and Even:
https://en.wikipedia.org/wiki/Parity_(mathematics)
You can extend the Swift BinaryInteger protocol to include a parity enumeration value:
enum Parity {
case even, odd
init<T>(_ integer: T) where T : BinaryInteger {
self = integer.isMultiple(of: 2) ? .even : .odd
}
}
extension BinaryInteger {
var parity: Parity { Parity(self) }
}
which enables you to switch on an integer and elegantly handle the two cases:
switch 42.parity {
case .even:
print("Even Number")
case .odd:
print("Odd Number")
}

You can use filter method:
let numbers = [1,2,3,4,5,6,7,8,9,10]
let odd = numbers.filter { $0 % 2 == 1 }
let even = numbers.filter { $0 % 2 == 0 }

Related

Error Handling in a Recursive Swift Function [duplicate]

I am making fuction that calculate factorial in swift. like this
func factorial(factorialNumber: UInt64) -> UInt64 {
if factorialNumber == 0 {
return 1
} else {
return factorialNumber * factorial(factorialNumber - 1)
}
}
let x = factorial(20)
this fuction can calculate untill 20.
I think factorial(21) value bigger than UINT64_MAX.
then How to calculate the 21! (21 factorial) in swift?
func factorial(_ n: Int) -> Double {
return (1...n).map(Double.init).reduce(1.0, *)
}
(1...n): We create an array of all the numbers that are involved in the operation (i.e: [1, 2, 3, ...]).
map(Double.init): We change from Int to Double because we can represent bigger numbers with Doubles than with Ints (https://en.wikipedia.org/wiki/Double-precision_floating-point_format). So, we now have the array of all the numbers that are involved in the operation as Doubles (i.e: [1.0, 2.0, 3.0, ...]).
reduce(1.0, *): We start multiplying 1.0 with the first element in the array (1.0*1.0 = 1.0), then the result of that with the next one (1.0*2.0 = 2.0), then the result of that with the next one (2.0*3.0 = 6.0), and so on.
Step 2 is to avoid the overflow issue.
Step 3 is to save us from explicitly defining a variable for keeping track of the partial results.
Unsigned 64 bit integer has a maximum value of 18,446,744,073,709,551,615. While 21! = 51,090,942,171,709,440,000. For this kind of case, you need a Big Integer type. I found a question about Big Integer in Swift. There's a library for Big Integer in that link.
BigInteger equivalent in Swift?
Did you think about using a double perhaps? Or NSDecimalNumber?
Also calling the same function recursively is really bad performance wise.
How about using a loop:
let value = number.intValue - 1
var product = NSDecimalNumber(value: number.intValue)
for i in (1...value).reversed() {
product = product.multiplying(by: NSDecimalNumber(value: i))
}
Here's a function that accepts any type that conforms to the Numeric protocol, which are all builtin number types.
func factorial<N: Numeric>(_ x: N) -> N {
x == 0 ? 1 : x * factorial(x - 1)
}
First we need to declare temp variable of type double so it can hold size of number.
Then we create a function that takes a parameter of type double.
Then we check, if the number equal 0 we can return or do nothing. We have an if condition so we can break the recursion of the function. Finally we return temp, which holds the factorial of given number.
var temp:Double = 1.0
func factorial(x:Double) -> Double{
if(x==0){
//do nothing
}else{
factorial(x: x-1)
temp *= x
}
return temp
}
factorial(x: 21.0)
I make function calculate factorial like this:
func factorialNumber( namber : Int ) -> Int {
var x = 1
for i in 1...namber {
x *= i
}
return x
}
print ( factorialNumber (namber : 5 ))
If you are willing to give up precision you can use a Double to roughly calculate factorials up to 170:
func factorial(_ n: Int) -> Double {
if n == 0 {
return 1
}
var a: Double = 1
for i in 1...n {
a *= Double(i)
}
return a
}
If not, use a big integer library.
func factoruial(_ num:Int) -> Int{
if num == 0 || num == 1{
return 1
}else{
return(num*factoruial(num - 1))
}
}
Using recursion to solve this problem:
func factorial(_ n: UInt) -> UInt {
return n < 2 ? 1 : n*factorial(n - 1)
}
func factorial(a: Int) -> Int {
return a == 1 ? a : a * factorial(a: a - 1)
}
print(factorial(a : 5))
print(factorial(a: 9))

Replacement for C-style loop in Swift 2.2

Swift 2.2 deprecated the C-style loop. However in some cases, the new range operator just doesn't work the same.
for var i = 0; i < -1; ++i { ... }
and
for i in 0..<-1 { ... }
The later one will fail at run-time. I can wrap the loop with an if, but it's a bit cluttered. Sometimes this kind of loop is useful.
Any thoughts?
Use cases
You need to enumerate all elements of an array, except the last one.
You need to enumerate all whole integer numbers in a decimal range, but the range can be like [0.5, 0.9] and so there's no integers (after some maths), which results in an empty loop.
Although it's not as "pretty", you can use stride:
for var i in 0.stride(to: -1, by: -1) {
print(i)
}
Mimicking the "C-style loop"
Not entirely pretty, but you can wrap the range:s upper bound with a max(0, ..) to ascertain it never takes negative values.
let foo : [Int] = []
for i in 0..<max(0,foo.count-1) {
print(i)
}
I'd prefer, however, the from.stride(to:by) solution (that has already been mentioned in the other answers, see e.g. Michael:s answer).
I think it's valuable to explicitly point out, however, that from.stride(to:by) neatly returns an empty StrideTo (or, if converted to an array: an empty array) if attempting to stride to a number that is less than from but by a positive stride. E.g., striding from 0 to -42 by 1 will not attempt to stride all the way through "∞ -> -∞ -> -42" (i.e., an error case), but simply returns an empty StrideTo (as it should):
Array(0.stride(to: -42, by: 1)) // []
// -> equivalent to your C loop:
for i in 0.stride(to: foo.count-1, by: 1) {
print(i)
}
Use case 1: enumerate all but the last element of an array
For this specific use case, a simple solution is using dropLast() (as described by Sulthan in the comments to your question) followed by forEach.
let foo = Array(1...5)
foo.dropLast().forEach { print($0) } // 1 2 3 4
Or, if you need more control over what to drop out, apply a filter to your array
let foo = Array(1...5)
foo.filter { $0 < foo.count }.forEach { print($0) } // 1 2 3 4
Use case 2: enumerate all integers in a decimal range, allowing this enumeration to be empty
For your decimal/double closed interval example ([0.6, 0.9]; an interval rather than a range in the context of Swift syntax), you can convert the closed interval to an integer range (using ceil function) and apply a forEach over the latter
let foo : (ClosedInterval<Double>) -> () = {
(Int(ceil($0.start))..<Int(ceil($0.end)))
.forEach { print($0) }
}
foo(0.5...1.9) // 1
foo(0.5...0.9) // nothing
Or, if you specifically want to enumerate the (possible) integers contained in this interval; use as en extension fit to your purpose:
protocol MyDoubleBounds {
func ceilToInt() -> Int
}
extension Double: MyDoubleBounds {
func ceilToInt() -> Int {
return Int(ceil(self)) // no integer bounds check in this simple example
}
}
extension ClosedInterval where Bound: MyDoubleBounds {
func enumerateIntegers() -> EnumerateSequence<(Range<Int>)> {
return (self.start.ceilToInt()
..< self.end.ceilToInt())
.enumerate()
}
}
Example usage:
for (i, intVal) in (1.3...3.2).enumerateIntegers() {
print(i, intVal)
} /* 0 2
1 3 */
for (i, intVal) in (0.6...0.9).enumerateIntegers() {
print(i, intVal)
} /* nothing */
For reference:
In swift 3.0 stride is now defined globally which makes for loop look more natural:
for i in stride(from: 10, to: 0, by: -1){
print(i)
} /* 10 9 8 7 6 5 4 3 2 1 */
For Swift 3 and need to change the "index"
for var index in stride(from: 0, to: 10, by: 1){}

Array return optional value? [duplicate]

If I have an array in Swift, and try to access an index that is out of bounds, there is an unsurprising runtime error:
var str = ["Apple", "Banana", "Coconut"]
str[0] // "Apple"
str[3] // EXC_BAD_INSTRUCTION
However, I would have thought with all the optional chaining and safety that Swift brings, it would be trivial to do something like:
let theIndex = 3
if let nonexistent = str[theIndex] { // Bounds check + Lookup
print(nonexistent)
...do other things with nonexistent...
}
Instead of:
let theIndex = 3
if (theIndex < str.count) { // Bounds check
let nonexistent = str[theIndex] // Lookup
print(nonexistent)
...do other things with nonexistent...
}
But this is not the case - I have to use the ol' if statement to check and ensure the index is less than str.count.
I tried adding my own subscript() implementation, but I'm not sure how to pass the call to the original implementation, or to access the items (index-based) without using subscript notation:
extension Array {
subscript(var index: Int) -> AnyObject? {
if index >= self.count {
NSLog("Womp!")
return nil
}
return ... // What?
}
}
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)
}
}
If you really want this behavior, it smells like you want a Dictionary instead of an Array. Dictionaries return nil when accessing missing keys, which makes sense because it's much harder to know if a key is present in a dictionary since those keys can be anything, where in an array the key must in a range of: 0 to count. And it's incredibly common to iterate over this range, where you can be absolutely sure have a real value on each iteration of a loop.
I think the reason it doesn't work this way is a design choice made by the Swift developers. Take your example:
var fruits: [String] = ["Apple", "Banana", "Coconut"]
var str: String = "I ate a \( fruits[0] )"
If you already know the index exists, as you do in most cases where you use an array, this code is great. However, if accessing a subscript could possibly return nil then you have changed the return type of Array's subscript method to be an optional. This changes your code to:
var fruits: [String] = ["Apple", "Banana", "Coconut"]
var str: String = "I ate a \( fruits[0]! )"
// ^ Added
Which means you would need to unwrap an optional every time you iterated through an array, or did anything else with a known index, just because rarely you might access an out of bounds index. The Swift designers opted for less unwrapping of optionals, at the expense of a runtime exception when accessing out of bounds indexes. And a crash is preferable to a logic error caused by a nil you didn't expect in your data somewhere.
And I agree with them. So you won't be changing the default Array implementation because you would break all the code that expects a non-optional values from arrays.
Instead, you could subclass Array, and override subscript to return an optional. Or, more practically, you could extend Array with a non-subscript method that does this.
extension Array {
// Safely lookup an index that might be out of bounds,
// returning nil if it does not exist
func get(index: Int) -> T? {
if 0 <= index && index < count {
return self[index]
} else {
return nil
}
}
}
var fruits: [String] = ["Apple", "Banana", "Coconut"]
if let fruit = fruits.get(1) {
print("I ate a \( fruit )")
// I ate a Banana
}
if let fruit = fruits.get(3) {
print("I ate a \( fruit )")
// never runs, get returned nil
}
Swift 3 Update
func get(index: Int) ->T? needs to be replaced by func get(index: Int) ->Element?
To build on Nikita Kukushkin's answer, sometimes you need to safely assign to array indexes as well as read from them, i.e.
myArray[safe: badIndex] = newValue
So here is an update to Nikita's answer (Swift 3.2) that also allows safely writing to mutable array indexes, by adding the safe: parameter name.
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
}
}
extension MutableCollection {
subscript(safe index: Index) -> Element? {
get {
return indices.contains(index) ? self[index] : nil
}
set(newValue) {
if let newValue = newValue, indices.contains(index) {
self[index] = newValue
}
}
}
}
extension Array {
subscript (safe index: Index) -> Element? {
0 <= index && index < count ? self[index] : nil
}
}
O(1) performance
type safe
correctly deals with Optionals for [MyType?] (returns MyType??, that can be unwrapped on both levels)
does not lead to problems for Sets
concise code
Here are some tests I ran for you:
let itms: [Int?] = [0, nil]
let a = itms[safe: 0] // 0 : Int??
a ?? 5 // 0 : Int?
let b = itms[safe: 1] // nil : Int??
b ?? 5 // nil : Int? (`b` contains a value and that value is `nil`)
let c = itms[safe: 2] // nil : Int??
c ?? 5 // 5 : Int?
Swift 4
An extension for those who prefer a more traditional syntax:
extension Array {
func item(at index: Int) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
Valid in Swift 2
Even though this has been answered plenty of times already, I'd like to present an answer more in line in where the fashion of Swift programming is going, which in Crusty's words¹ is: "Think protocols first"
• What do we want to do?
- Get an Element of an Array given an Index only when it's safe, and nil otherwise
• What should this functionality base it's implementation on?
- Array subscripting
• Where does it get this feature from?
- Its definition of struct Array in the Swift module has it
• Nothing more generic/abstract?
- It adopts protocol CollectionType which ensures it as well
• Nothing more generic/abstract?
- It adopts protocol Indexable as well...
• Yup, sounds like the best we can do. Can we then extend it to have this feature we want?
- But we have very limited types (no Int) and properties (no count) to work with now!
• It will be enough. Swift's stdlib is done pretty well ;)
extension Indexable {
public subscript(safe safeIndex: Index) -> _Element? {
return safeIndex.distanceTo(endIndex) > 0 ? self[safeIndex] : nil
}
}
¹: not true, but it gives the idea
Because arrays may store nil values, it does not make sense to return a nil if an array[index] call is out of bounds.
Because we do not know how a user would like to handle out of bounds problems, it does not make sense to use custom operators.
In contrast, use traditional control flow for unwrapping objects and ensure type safety.
if let index = array.checkIndexForSafety(index:Int)
let item = array[safeIndex: index]
if let index = array.checkIndexForSafety(index:Int)
array[safeIndex: safeIndex] = myObject
extension Array {
#warn_unused_result public func checkIndexForSafety(index: Int) -> SafeIndex? {
if indices.contains(index) {
// wrap index number in object, so can ensure type safety
return SafeIndex(indexNumber: index)
} else {
return nil
}
}
subscript(index:SafeIndex) -> Element {
get {
return self[index.indexNumber]
}
set {
self[index.indexNumber] = newValue
}
}
// second version of same subscript, but with different method signature, allowing user to highlight using safe index
subscript(safeIndex index:SafeIndex) -> Element {
get {
return self[index.indexNumber]
}
set {
self[index.indexNumber] = newValue
}
}
}
public class SafeIndex {
var indexNumber:Int
init(indexNumber:Int){
self.indexNumber = indexNumber
}
}
I realize this is an old question. I'm using Swift5.1 at this point, the OP was for Swift 1 or 2?
I needed something like this today, but I didn't want to add a full scale extension for just the one place and wanted something more functional (more thread safe?). I also didn't need to protect against negative indices, just those that might be past the end of an array:
let fruit = ["Apple", "Banana", "Coconut"]
let a = fruit.dropFirst(2).first // -> "Coconut"
let b = fruit.dropFirst(0).first // -> "Apple"
let c = fruit.dropFirst(10).first // -> nil
For those arguing about Sequences with nil's, what do you do about the first and last properties that return nil for empty collections?
I liked this because I could just grab at existing stuff and use it to get the result I wanted. I also know that dropFirst(n) is not a whole collection copy, just a slice. And then the already existent behavior of first takes over for me.
I found safe array get, set, insert, remove very useful. I prefer to log and ignore the errors as all else soon gets hard to manage. Full code bellow
/**
Safe array get, set, insert and delete.
All action that would cause an error are ignored.
*/
extension Array {
/**
Removes element at index.
Action that would cause an error are ignored.
*/
mutating func remove(safeAt index: Index) {
guard index >= 0 && index < count else {
print("Index out of bounds while deleting item at index \(index) in \(self). This action is ignored.")
return
}
remove(at: index)
}
/**
Inserts element at index.
Action that would cause an error are ignored.
*/
mutating func insert(_ element: Element, safeAt index: Index) {
guard index >= 0 && index <= count else {
print("Index out of bounds while inserting item at index \(index) in \(self). This action is ignored")
return
}
insert(element, at: index)
}
/**
Safe get set subscript.
Action that would cause an error are ignored.
*/
subscript (safe index: Index) -> Element? {
get {
return indices.contains(index) ? self[index] : nil
}
set {
remove(safeAt: index)
if let element = newValue {
insert(element, safeAt: index)
}
}
}
}
Tests
import XCTest
class SafeArrayTest: XCTestCase {
func testRemove_Successful() {
var array = [1, 2, 3]
array.remove(safeAt: 1)
XCTAssert(array == [1, 3])
}
func testRemove_Failure() {
var array = [1, 2, 3]
array.remove(safeAt: 3)
XCTAssert(array == [1, 2, 3])
}
func testInsert_Successful() {
var array = [1, 2, 3]
array.insert(4, safeAt: 1)
XCTAssert(array == [1, 4, 2, 3])
}
func testInsert_Successful_AtEnd() {
var array = [1, 2, 3]
array.insert(4, safeAt: 3)
XCTAssert(array == [1, 2, 3, 4])
}
func testInsert_Failure() {
var array = [1, 2, 3]
array.insert(4, safeAt: 5)
XCTAssert(array == [1, 2, 3])
}
func testGet_Successful() {
var array = [1, 2, 3]
let element = array[safe: 1]
XCTAssert(element == 2)
}
func testGet_Failure() {
var array = [1, 2, 3]
let element = array[safe: 4]
XCTAssert(element == nil)
}
func testSet_Successful() {
var array = [1, 2, 3]
array[safe: 1] = 4
XCTAssert(array == [1, 4, 3])
}
func testSet_Successful_AtEnd() {
var array = [1, 2, 3]
array[safe: 3] = 4
XCTAssert(array == [1, 2, 3, 4])
}
func testSet_Failure() {
var array = [1, 2, 3]
array[safe: 4] = 4
XCTAssert(array == [1, 2, 3])
}
}
Swift 5.x
An extension on RandomAccessCollection means that this can also work for ArraySlice from a single implementation. We use startIndex and endIndex as array slices use the indexes from the underlying parent Array.
public extension RandomAccessCollection {
/// Returns the element at the specified index if it is within bounds, otherwise nil.
/// - complexity: O(1)
subscript (safe index: Index) -> Element? {
guard index >= startIndex, index < endIndex else {
return nil
}
return self[index]
}
}
extension Array {
subscript (safe index: UInt) -> Element? {
return Int(index) < count ? self[Int(index)] : nil
}
}
Using Above mention extension return nil if anytime index goes out of bound.
let fruits = ["apple","banana"]
print("result-\(fruits[safe : 2])")
result - nil
I have padded the array with nils in my use case:
let components = [1, 2]
var nilComponents = components.map { $0 as Int? }
nilComponents += [nil, nil, nil]
switch (nilComponents[0], nilComponents[1], nilComponents[2]) {
case (_, _, .Some(5)):
// process last component with 5
default:
break
}
Also check the subscript extension with safe: label by Erica Sadun / Mike Ash: http://ericasadun.com/2015/06/01/swift-safe-array-indexing-my-favorite-thing-of-the-new-week/
The "Commonly Rejected Changes" for Swift list contains a mention of changing Array subscript access to return an optional rather than crashing:
Make Array<T> subscript access return T? or T! instead of T: The current array behavior is intentional, as it accurately reflects the fact that out-of-bounds array access is a logic error. Changing the current behavior would slow Array accesses to an unacceptable degree. This topic has come up multiple times before but is very unlikely to be accepted.
https://github.com/apple/swift-evolution/blob/master/commonly_proposed.md#strings-characters-and-collection-types
So the basic subscript access will not be changing to return an optional.
However, the Swift team/community does seem open to adding a new optional-returning access pattern to Arrays, either via a function or subscript.
This has been proposed and discussed on the Swift Evolution forum here:
https://forums.swift.org/t/add-accessor-with-bounds-check-to-array/16871
Notably, Chris Lattner gave the idea a "+1":
Agreed, the most frequently suggested spelling for this is: yourArray[safe: idx], which seems great to me. I am very +1 for adding this.
https://forums.swift.org/t/add-accessor-with-bounds-check-to-array/16871/13
So this may be possible out of the box in some future version of Swift. I'd encourage anyone who wants it to contribute to that Swift Evolution thread.
Not sure why no one, has put up an extension that also has a setter to automatically grow the array
extension Array where Element: ExpressibleByNilLiteral {
public subscript(safe index: Int) -> Element? {
get {
guard index >= 0, index < endIndex else {
return nil
}
return self[index]
}
set(newValue) {
if index >= endIndex {
self.append(contentsOf: Array(repeating: nil, count: index - endIndex + 1))
}
self[index] = newValue ?? nil
}
}
}
Usage is easy and works as of Swift 5.1
var arr:[String?] = ["A","B","C"]
print(arr) // Output: [Optional("A"), Optional("B"), Optional("C")]
arr[safe:10] = "Z"
print(arr) // [Optional("A"), Optional("B"), Optional("C"), nil, nil, nil, nil, nil, nil, nil, Optional("Z")]
Note: You should understand the performance cost (both in time/space) when growing an array in swift - but for small problems sometimes you just need to get Swift to stop Swifting itself in the foot
To propagate why operations fail, errors are better than optionals.
public extension Collection {
/// Ensure an index is valid before accessing an element of the collection.
/// - Returns: The same as the unlabeled subscript, if an error is not thrown.
/// - Throws: `AnyCollection<Element>.IndexingError`
/// if `indices` does not contain `index`.
subscript(validating index: Index) -> Element {
get throws {
guard indices.contains(index)
else { throw AnyCollection<Element>.IndexingError() }
return self[index]
}
}
}
public extension AnyCollection {
/// Thrown when `[validating:]` is called with an invalid index.
struct IndexingError: Error { }
}
XCTAssertThrowsError(try ["🐾", "🥝"][validating: 2])
let collection = Array(1...10)
XCTAssertEqual(try collection[validating: 0], 1)
XCTAssertThrowsError(try collection[validating: collection.endIndex]) {
XCTAssert($0 is AnyCollection<Int>.IndexingError)
}
I think this is not a good idea. It seems preferable to build solid code that does not result in trying to apply out-of-bounds indexes.
Please consider that having such an error fail silently (as suggested by your code above) by returning nil is prone to producing even more complex, more intractable errors.
You could do your override in a similar fashion you used and just write the subscripts in your own way. Only drawback is that existing code will not be compatible. I think to find a hook to override the generic x[i] (also without a text preprocessor as in C) will be challenging.
The closest I can think of is
// compile error:
if theIndex < str.count && let existing = str[theIndex]
EDIT: This actually works. One-liner!!
func ifInBounds(array: [AnyObject], idx: Int) -> AnyObject? {
return idx < array.count ? array[idx] : nil
}
if let x: AnyObject = ifInBounds(swiftarray, 3) {
println(x)
}
else {
println("Out of bounds")
}
I have made a simple extension for array
extension Array where Iterator.Element : AnyObject {
func iof (_ i : Int ) -> Iterator.Element? {
if self.count > i {
return self[i] as Iterator.Element
}
else {
return nil
}
}
}
it works perfectly as designed
Example
if let firstElemntToLoad = roots.iof(0)?.children?.iof(0)?.cNode,
You can try
if index >= 0 && index < array.count {
print(array[index])
}
To be honest I faced this issue too. And from performance point of view a Swift array should be able to throw.
let x = try a[y]
This would be nice and understandable.
When you only need to get values from an array and you don't mind a small performance penalty (i.e. if your collection isn't huge), there is a Dictionary-based alternative that doesn't involve (a too generic, for my taste) collection extension:
// Assuming you have a collection named array:
let safeArray = Dictionary(uniqueKeysWithValues: zip(0..., array))
let value = safeArray[index] ?? defaultValue;
2022
infinite index access and safe idx access(returns nil in case no such idex):
public extension Collection {
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
subscript (infinityIdx idx: Index) -> Element where Index == Int {
return self[ abs(idx) % self.count ]
}
}
but be careful, it will throw an exception in case of array/collection is empty
usage
(0...10)[safe: 11] // nil
(0...10)[infinityIdx: 11] // 0
(0...10)[infinityIdx: 12] // 1
(0...10)[infinityIdx: 21] // 0
(0...10)[infinityIdx: 22] // 1
Swift 5 Usage
extension WKNavigationType {
var name : String {
get {
let names = ["linkAct","formSubm","backForw","reload","formRelo"]
return names.indices.contains(self.rawValue) ? names[self.rawValue] : "other"
}
}
}
ended up with but really wanted to do generally like
[<collection>][<index>] ?? <default>
but as the collection is contextual I guess it's proper.

Swift: get number of values in an enum? Goal is to avoid hard coding number in random function [duplicate]

How can I determine the number of cases in a Swift enum?
(I would like to avoid manually enumerating through all the values, or using the old "enum_count trick" if possible.)
As of Swift 4.2 (Xcode 10) you can declare
conformance to the CaseIterable protocol, this works for all
enumerations without associated values:
enum Stuff: CaseIterable {
case first
case second
case third
case forth
}
The number of cases is now simply obtained with
print(Stuff.allCases.count) // 4
For more information, see
SE-0194 Derived Collection of Enum Cases
I have a blog post that goes into more detail on this, but as long as your enum's raw type is an integer, you can add a count this way:
enum Reindeer: Int {
case Dasher, Dancer, Prancer, Vixen, Comet, Cupid, Donner, Blitzen
case Rudolph
static let count: Int = {
var max: Int = 0
while let _ = Reindeer(rawValue: max) { max += 1 }
return max
}()
}
Xcode 10 update
Adopt the CaseIterable protocol in the enum, it provides a static allCases property which contains all enum cases as a Collection . Just use of its count property to know how many cases the enum has.
See Martin's answer for an example (and upvote his answers rather than mine)
Warning: the method below doesn't seem to work anymore.
I'm not aware of any generic method to count the number of enum cases. I've noticed however that the hashValue property of the enum cases is incremental, starting from zero, and with the order determined by the order in which the cases are declared. So, the hash of the last enum plus one corresponds to the number of cases.
For example with this enum:
enum Test {
case ONE
case TWO
case THREE
case FOUR
static var count: Int { return Test.FOUR.hashValue + 1}
}
count returns 4.
I cannot say if that's a rule or if it will ever change in the future, so use at your own risk :)
I define a reusable protocol which automatically performs the case count based on the approach posted by Nate Cook.
protocol CaseCountable {
static var caseCount: Int { get }
}
extension CaseCountable where Self: RawRepresentable, Self.RawValue == Int {
internal static var caseCount: Int {
var count = 0
while let _ = Self(rawValue: count) {
count += 1
}
return count
}
}
Then I can reuse this protocol for example as follows:
enum Planet : Int, CaseCountable {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
//..
print(Planet.caseCount)
Create static allValues array as shown in this answer
enum ProductCategory : String {
case Washers = "washers", Dryers = "dryers", Toasters = "toasters"
static let allValues = [Washers, Dryers, Toasters]
}
...
let count = ProductCategory.allValues.count
This is also helpful when you want to enumerate the values, and works for all Enum types
If the implementation doesn't have anything against using integer enums, you could add an extra member value called Count to represent the number of members in the enum - see example below:
enum TableViewSections : Int {
case Watchlist
case AddButton
case Count
}
Now you can get the number of members in the enum by calling, TableViewSections.Count.rawValue which will return 2 for the example above.
When you're handling the enum in a switch statement, make sure to throw an assertion failure when encountering the Count member where you don't expect it:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let currentSection: TableViewSections = TableViewSections.init(rawValue:section)!
switch(currentSection) {
case .Watchlist:
return watchlist.count
case .AddButton:
return 1
case .Count:
assert(false, "Invalid table view section!")
}
}
This kind of function is able to return the count of your enum.
Swift 2:
func enumCount<T: Hashable>(_: T.Type) -> Int {
var i = 1
while (withUnsafePointer(&i) { UnsafePointer<T>($0).memory }).hashValue != 0 {
i += 1
}
return i
}
Swift 3:
func enumCount<T: Hashable>(_: T.Type) -> Int {
var i = 1
while (withUnsafePointer(to: &i, {
return $0.withMemoryRebound(to: T.self, capacity: 1, { return $0.pointee })
}).hashValue != 0) {
i += 1
}
return i
}
String Enum with Index
enum eEventTabType : String {
case Search = "SEARCH"
case Inbox = "INBOX"
case Accepted = "ACCEPTED"
case Saved = "SAVED"
case Declined = "DECLINED"
case Organized = "ORGANIZED"
static let allValues = [Search, Inbox, Accepted, Saved, Declined, Organized]
var index : Int {
return eEventTabType.allValues.indexOf(self)!
}
}
count : eEventTabType.allValues.count
index : objeEventTabType.index
Enjoy :)
Oh hey everybody, what about unit tests?
func testEnumCountIsEqualToNumberOfItemsInEnum() {
var max: Int = 0
while let _ = Test(rawValue: max) { max += 1 }
XCTAssert(max == Test.count)
}
This combined with Antonio's solution:
enum Test {
case one
case two
case three
case four
static var count: Int { return Test.four.hashValue + 1}
}
in the main code gives you O(1) plus you get a failing test if someone adds an enum case five and doesn't update the implementation of count.
This function relies on 2 undocumented current(Swift 1.1) enum behavior:
Memory layout of enum is just a index of case. If case count is from 2 to 256, it's UInt8.
If the enum was bit-casted from invalid case index, its hashValue is 0
So use at your own risk :)
func enumCaseCount<T:Hashable>(t:T.Type) -> Int {
switch sizeof(t) {
case 0:
return 1
case 1:
for i in 2..<256 {
if unsafeBitCast(UInt8(i), t).hashValue == 0 {
return i
}
}
return 256
case 2:
for i in 257..<65536 {
if unsafeBitCast(UInt16(i), t).hashValue == 0 {
return i
}
}
return 65536
default:
fatalError("too many")
}
}
Usage:
enum Foo:String {
case C000 = "foo"
case C001 = "bar"
case C002 = "baz"
}
enumCaseCount(Foo) // -> 3
I wrote a simple extension which gives all enums where raw value is integer a count property:
extension RawRepresentable where RawValue: IntegerType {
static var count: Int {
var i: RawValue = 0
while let _ = Self(rawValue: i) {
i = i.successor()
}
return Int(i.toIntMax())
}
}
Unfortunately it gives the count property to OptionSetType where it won't work properly, so here is another version which requires explicit conformance to CaseCountable protocol for any enum which cases you want to count:
protocol CaseCountable: RawRepresentable {}
extension CaseCountable where RawValue: IntegerType {
static var count: Int {
var i: RawValue = 0
while let _ = Self(rawValue: i) {
i = i.successor()
}
return Int(i.toIntMax())
}
}
It's very similar to the approach posted by Tom Pelaia, but works with all integer types.
enum EnumNameType: Int {
case first
case second
case third
static var count: Int { return EnumNameType.third.rawValue + 1 }
}
print(EnumNameType.count) //3
OR
enum EnumNameType: Int {
case first
case second
case third
case count
}
print(EnumNameType.count.rawValue) //3
*On Swift 4.2 (Xcode 10) can use:
enum EnumNameType: CaseIterable {
case first
case second
case third
}
print(EnumNameType.allCases.count) //3
Of course, it's not dynamic but for many uses you can get by with a static var added to your Enum
static var count: Int{ return 7 }
and then use it as EnumName.count
For my use case, in a codebase where multiple people could be adding keys to an enum, and these cases should all be available in the allKeys property, it's important that allKeys be validated against the keys in the enum. This is to avoid someone forgetting to add their key to the all keys list. Matching the count of the allKeys array(first created as a set to avoid dupes) against the number of keys in the enum ensures that they are all present.
Some of the answers above show the way to achieve this in Swift 2 but none work in Swift 3. Here is the Swift 3 formatted version:
static func enumCount<T: Hashable>(_ t: T.Type) -> Int {
var i = 1
while (withUnsafePointer(to: &i) {
$0.withMemoryRebound(to:t.self, capacity:1) { $0.pointee.hashValue != 0 }
}) {
i += 1
}
return i
}
static var allKeys: [YourEnumTypeHere] {
var enumSize = enumCount(YourEnumTypeHere.self)
let keys: Set<YourEnumTypeHere> = [.all, .your, .cases, .here]
guard keys.count == enumSize else {
fatalError("Missmatch between allKeys(\(keys.count)) and actual keys(\(enumSize)) in enum.")
}
return Array(keys)
}
Depending on your use case, you might want to just run the test in development to avoid the overhead of using allKeys on each request
Why do you make it all so complex? The SIMPLEST counter of Int enum is to add:
case Count
In the end. And... viola - now you have the count - fast and simple
enum WeekDays : String , CaseIterable
{
case monday = "Mon"
case tuesday = "Tue"
case wednesday = "Wed"
case thursday = "Thu"
case friday = "Fri"
case saturday = "Sat"
case sunday = "Sun"
}
var weekdays = WeekDays.AllCases()
print("\(weekdays.count)")
If you don't want to base your code in the last enum you can create this function inside your enum.
func getNumberOfItems() -> Int {
var i:Int = 0
var exit:Bool = false
while !exit {
if let menuIndex = MenuIndex(rawValue: i) {
i++
}else{
exit = true
}
}
return i
}
A Swift 3 version working with Int type enums:
protocol CaseCountable: RawRepresentable {}
extension CaseCountable where RawValue == Int {
static var count: RawValue {
var i: RawValue = 0
while let _ = Self(rawValue: i) { i += 1 }
return i
}
}
Credits: Based on the answers by bzz and Nate Cook.
Generic IntegerType (in Swift 3 renamed to Integer) is not supported, as it's a heavily fragmented generic type which lacks a lot of functions. successor is not available with Swift 3 anymore.
Be aware that the comment from Code Commander to Nate Cooks answer is still valid:
While nice because you don't need to hardcode a value, this will
instantiate every enum value each time it is called. That is O(n)
instead of O(1).
As far as I know there is currently no workaround when using this as protocol extension (and not implementing in each enum like Nate Cook did) due to static stored properties not being supported in generic types.
Anyway, for small enums this should be no issue. A typical use case would be the section.count for UITableViews as already mentioned by Zorayr.
Extending Matthieu Riegler answer, this is a solution for Swift 3 that doesn't require the use of generics, and can be easily called using the enum type with EnumType.elementsCount:
extension RawRepresentable where Self: Hashable {
// Returns the number of elements in a RawRepresentable data structure
static var elementsCount: Int {
var i = 1
while (withUnsafePointer(to: &i, {
return $0.withMemoryRebound(to: self, capacity: 1, { return
$0.pointee })
}).hashValue != 0) {
i += 1
}
return i
}
I solved this problem for myself by creating a protocol (EnumIntArray) and a global utility function (enumIntArray) that make it very easy to add an "All" variable to any enum (using swift 1.2). The "all" variable will contain an array of all elements in the enum so you can use all.count for the count
It only works with enums that use raw values of type Int but perhaps it can provide some inspiration for other types.
It also addresses the "gap in numbering" and "excessive time to iterate" issues I've read above and elsewhere.
The idea is to add the EnumIntArray protocol to your enum and then define an "all" static variable by calling the enumIntArray function and provide it with the first element (and the last if there are gaps in the numbering).
Because the static variable is only initialized once, the overhead of going through all raw values only hits your program once.
example (without gaps) :
enum Animals:Int, EnumIntArray
{
case Cat=1, Dog, Rabbit, Chicken, Cow
static var all = enumIntArray(Animals.Cat)
}
example (with gaps) :
enum Animals:Int, EnumIntArray
{
case Cat = 1, Dog,
case Rabbit = 10, Chicken, Cow
static var all = enumIntArray(Animals.Cat, Animals.Cow)
}
Here's the code that implements it:
protocol EnumIntArray
{
init?(rawValue:Int)
var rawValue:Int { get }
}
func enumIntArray<T:EnumIntArray>(firstValue:T, _ lastValue:T? = nil) -> [T]
{
var result:[T] = []
var rawValue = firstValue.rawValue
while true
{
if let enumValue = T(rawValue:rawValue++)
{ result.append(enumValue) }
else if lastValue == nil
{ break }
if lastValue != nil
&& rawValue > lastValue!.rawValue
{ break }
}
return result
}
Or you can just define the _count outside the enum, and attach it statically:
let _count: Int = {
var max: Int = 0
while let _ = EnumName(rawValue: max) { max += 1 }
return max
}()
enum EnumName: Int {
case val0 = 0
case val1
static let count = _count
}
That way no matter how many enums you create, it'll only ever be created once.
(delete this answer if static does that)
The following method comes from CoreKit and is similar to the answers some others have suggested. This works with Swift 4.
public protocol EnumCollection: Hashable {
static func cases() -> AnySequence<Self>
static var allValues: [Self] { get }
}
public extension EnumCollection {
public static func cases() -> AnySequence<Self> {
return AnySequence { () -> AnyIterator<Self> in
var raw = 0
return AnyIterator {
let current: Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: self, capacity: 1) { $0.pointee } }
guard current.hashValue == raw else {
return nil
}
raw += 1
return current
}
}
}
public static var allValues: [Self] {
return Array(self.cases())
}
}
enum Weekdays: String, EnumCollection {
case sunday, monday, tuesday, wednesday, thursday, friday, saturday
}
Then you just need to just call Weekdays.allValues.count.
Just want to share a solution when you have an enum with associated values.
enum SomeEnum {
case one
case two(String)
case three(String, Int)
}
CaseIterable doesn't provide allCases automatically.
We can't provide a raw type like Int for your enum to calculate cases count somehow.
What we can do is to use power of switch and fallthrough keyword.
extension SomeEnum {
static var casesCount: Int {
var sum = 0
switch Self.one { // Potential problem
case one:
sum += 1
fallthrough
case two:
sum += 1
fallthrough
case three:
sum += 1
}
return sum
}
}
So now you can say SomeEnum.casesCount.
Remarks:
We still have a problem with switch Self.one {..., we hardcoded the first case. You can easily hack this solution. But I used it just for unit tests so that was not a problem.
If you often need to get cases count in enums with associated values, think about code generation.
struct HashableSequence<T: Hashable>: SequenceType {
func generate() -> AnyGenerator<T> {
var i = 0
return AnyGenerator {
let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory }
if next.hashValue == i {
i += 1
return next
}
return nil
}
}
}
extension Hashable {
static func enumCases() -> Array<Self> {
return Array(HashableSequence())
}
static var enumCount: Int {
return enumCases().enumCount
}
}
enum E {
case A
case B
case C
}
E.enumCases() // [A, B, C]
E.enumCount // 3
but be careful with usage on non-enum types. Some workaround could be:
struct HashableSequence<T: Hashable>: SequenceType {
func generate() -> AnyGenerator<T> {
var i = 0
return AnyGenerator {
guard sizeof(T) == 1 else {
return nil
}
let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory }
if next.hashValue == i {
i += 1
return next
}
return nil
}
}
}
extension Hashable {
static func enumCases() -> Array<Self> {
return Array(HashableSequence())
}
static var enumCount: Int {
return enumCases().count
}
}
enum E {
case A
case B
case C
}
Bool.enumCases() // [false, true]
Bool.enumCount // 2
String.enumCases() // []
String.enumCount // 0
Int.enumCases() // []
Int.enumCount // 0
E.enumCases() // [A, B, C]
E.enumCount // 4
It can use a static constant which contains the last value of the enumeration plus one.
enum Color : Int {
case Red, Orange, Yellow, Green, Cyan, Blue, Purple
static let count: Int = Color.Purple.rawValue + 1
func toUIColor() -> UIColor{
switch self {
case .Red:
return UIColor.redColor()
case .Orange:
return UIColor.orangeColor()
case .Yellow:
return UIColor.yellowColor()
case .Green:
return UIColor.greenColor()
case .Cyan:
return UIColor.cyanColor()
case .Blue:
return UIColor.blueColor()
case .Purple:
return UIColor.redColor()
}
}
}
This is minor, but I think a better O(1) solution would be the following (ONLY if your enum is Int starting at x, etc.):
enum Test : Int {
case ONE = 1
case TWO
case THREE
case FOUR // if you later need to add additional enums add above COUNT so COUNT is always the last enum value
case COUNT
static var count: Int { return Test.COUNT.rawValue } // note if your enum starts at 0, some other number, etc. you'll need to add on to the raw value the differential
}
The current selected answer I still believe is the best answer for all enums, unless you are working with Int then I recommend this solution.

In Swift, how to convert String to Int for base 2 though base 36 like Long.parseLong in Java?

How do I convert a String to a Long in Swift?
In Java I would do Long.parseLong("str", Character.MAX_RADIX).
We now have these conversion functions built-in in Swift Standard Library:
Encode using base 2 through 36: https://developer.apple.com/documentation/swift/string/2997127-init
Decode using base 2 through 36: https://developer.apple.com/documentation/swift/int/2924481-init
As noted here, you can use the standard library function strtoul():
let base36 = "1ARZ"
let number = strtoul(base36, nil, 36)
println(number) // Output: 60623
The third parameter is the radix. See the man page for how the function handles whitespace and other details.
Here is parseLong() in Swift. Note that the function returns an Int? (optional Int) that must be unwrapped to be used.
// Function to convert a String to an Int?. It returns nil
// if the string contains characters that are not valid digits
// in the base or if the number is too big to fit in an Int.
func parseLong(string: String, base: Int) -> Int? {
let digits = Array("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
var number = 0
for char in string.uppercaseString {
if let digit = find(digits, char) {
if digit < base {
// Compute the value of the number so far
// allowing for overflow
let newnumber = number &* base &+ digit
// Check for overflow and return nil if
// it did overflow
if newnumber < number {
return nil
}
number = newnumber
} else {
// Invalid digit for the base
return nil
}
} else {
// Invalid character not in digits
return nil
}
}
return number
}
if let result = parseLong("1110", 2) {
println("1110 in base 2 is \(result)") // "1110 in base 2 is 14"
}
if let result = parseLong("ZZ", 36) {
println("ZZ in base 36 is \(result)") // "ZZ in base 36 is 1295"
}
Swift ways:
"123".toInt() // Return an optional
C way:
atol("1232")
Or use the NSString's integerValue method
("123" as NSString).integerValue

Resources