Making an Array of Integers in iOS

Making an array of integers in iOS

You can use a plain old C array:

NSInteger myIntegers[40];

for (NSInteger i = 0; i < 40; i++)
myIntegers[i] = i;

// to get one of them
NSLog (@"The 4th integer is: %d", myIntegers[3]);

Or, you can use an NSArray or NSMutableArray, but here you will need to wrap up each integer inside an NSNumber instance (because NSArray objects are designed to hold class instances).

NSMutableArray *myIntegers = [NSMutableArray array];

for (NSInteger i = 0; i < 40; i++)
[myIntegers addObject:[NSNumber numberWithInteger:i]];

// to get one of them
NSLog (@"The 4th integer is: %@", [myIntegers objectAtIndex:3]);

// or
NSLog (@"The 4th integer is: %d", [[myIntegers objectAtIndex:3] integerValue]);

How to create an array with incremented values in Swift?]

Use the ... notation / operator:

let arr1 = 0...4

That gets you a Range, which you can easily turn into a "regular" Array:

let arr2 = Array(0...4)

Create a range or array of integers up to a total int number]

You could use an Int's array initializer with a range.

Either:

let arr = [Int](1...4)

or:

let arr = Array(1...4)

Result:

[1, 2, 3, 4]

let num = 4

let arr = Array(1...num)

Array of strings and ints in swift

I think what you want is an array of tuples, not an array of arrays. That implementation would look like this:

let items: [(String, Int)] = [("A", 1), ("B", 2), ("C", 3)]

You could access these properties like this:

let itemOneString = items[0].0 // "A"
let itemOneInt = items[0].1 // 1

Is there a way to instantly generate an array filled with a range of values in Swift?

You can create an array with a range like this:

var values = Array(0...100)

This give you an array of [0, ..., 100]

How to use for loop to create Int array in Swift 3

Your array is empty and you are subscripting to assign value thats why you are getting "Array index out of range" crash. If you want to go with for loop then.

var integerArray = [Int]()
for i in 0...100 {
integerArray.append(i)
}

But instead of that you can create array simply like this no need to use for loop.

var integerArray = [Int](0...100)

Create an array of random numbers in Swift

In Swift 4.2 there is a new static method for fixed width integers that makes the syntax more user friendly:

func makeList(_ n: Int) -> [Int] {
return (0..<n).map { _ in .random(in: 1...20) }
}

Edit/update: Swift 5.1 or later

We can also extend Range and ClosedRange and create a method to return n random elements:

extension RangeExpression where Bound: FixedWidthInteger {
func randomElements(_ n: Int) -> [Bound] {
precondition(n > 0)
switch self {
case let range as Range<Bound>: return (0..<n).map { _ in .random(in: range) }
case let range as ClosedRange<Bound>: return (0..<n).map { _ in .random(in: range) }
default: return []
}
}
}

extension Range where Bound: FixedWidthInteger {
var randomElement: Bound { .random(in: self) }
}

extension ClosedRange where Bound: FixedWidthInteger {
var randomElement: Bound { .random(in: self) }
}

Usage:

let randomElements = (1...20).randomElements(5)  // [17, 16, 2, 15, 12]
randomElements.sorted() // [2, 12, 15, 16, 17]

let randomElement = (1...20).randomElement // 4 (note that the computed property returns a non-optional instead of the default method which returns an optional)

let randomElements = (0..<2).randomElements(5)  // [1, 0, 1, 1, 1]
let randomElement = (0..<2).randomElement // 0

Note: for Swift 3, 4 and 4.1 and earlier click here.

How to convert Data/NSData to an Array of Integers using Swift

1) If you have stingyfy josn(Come from API response) then you can convert to directly to [Int] using..

do {
let IntArray = try JSONSerialization.jsonObject(with: dataObject, options:[])
print(IntArray)
// print: 1,2,3,4,5,6,7,8,9
}catch{
print("Error in Serialization")
}

2) If you want [Int] and Data conversion then use this

You can create Data from [Int] using 'archivedData' and back to '[Int]' using unarchiveObject.

var listOfInt : [Int] = [1,2,3,4,5,6,7,8,9]

let dataObject = NSKeyedArchiver.archivedData(withRootObject: listOfInt)

if let objects = NSKeyedUnarchiver.unarchiveObject(with: dataObject) as? [Int] {
print(objects)
// print: 1,2,3,4,5,6,7,8,9
} else {
print("Error while unarchiveObject")
}

How to create an empty array in Swift?

Here you go:

var yourArray = [String]()

The above also works for other types and not just strings. It's just an example.

Adding Values to It

I presume you'll eventually want to add a value to it!

yourArray.append("String Value")

Or

let someString = "You can also pass a string variable, like this!"
yourArray.append(someString)

Add by Inserting

Once you have a few values, you can insert new values instead of appending. For example, if you wanted to insert new objects at the beginning of the array (instead of appending them to the end):

yourArray.insert("Hey, I'm first!", atIndex: 0)

Or you can use variables to make your insert more flexible:

let lineCutter = "I'm going to be first soon."
let positionToInsertAt = 0
yourArray.insert(lineCutter, atIndex: positionToInsertAt)

You May Eventually Want to Remove Some Stuff

var yourOtherArray = ["MonkeysRule", "RemoveMe", "SwiftRules"]
yourOtherArray.remove(at: 1)

The above works great when you know where in the array the value is (that is, when you know its index value). As the index values begin at 0, the second entry will be at index 1.

Removing Values Without Knowing the Index

But what if you don't? What if yourOtherArray has hundreds of values and all you know is you want to remove the one equal to "RemoveMe"?

if let indexValue = yourOtherArray.index(of: "RemoveMe") {
yourOtherArray.remove(at: indexValue)
}

This should get you started!



Related Topics



Leave a reply



Submit