UInt8 Array to Strings in Swift - arrays

I want to convert an Array of UInt8 to several strings
var BytesArray = [123, 9, 32, 236]
TO
var Srt0 = "123"
var Srt1 = "9"
var Srt2 = "32"
var Srt3 = "236"

As you say, the answer should be like that-
var BytesArray = [123, 9, 32, 236]
var sort0:String = String(BytesArray[0])
var sort1:String = String(BytesArray[1])
var sort2:String = String(BytesArray[2])
var sort3:String = String(BytesArray[3])

Do you mean the following?
var bytesArray = [123, 9, 32, 236]
let stringArray = bytesArray.map( { "\($0)" })
print(stringArray)
This will produce an array of strings.

var BytesArray: [Int] = [123, 9, 32, 236]
var stringArray = BytesArray.map
{
String($0)
}
stringArray will become ["123", "9", "32", "236"]

Related

Matching two array key and combine it's value with google app script

I have two formatted array as below code, and I would like to match the id and get the matched id value of size and stock
I have the code from github as below but can not get it to work
var arraysize = [];
var arraycode = [];
var code = '{id:'+stock[i][1] +',stock:'+ stock[i][4]+'}';
var size = '{id:'+tomatchcode+',size:'+tomatchsize+'}';
arraycode[i] = code;
arraysize[i] = size;
Logger.log(arraysize);
Logger.log(arraycode);
[19-08-29 10:32:35:003 ICT] [{id:59,size:36}, {id:123,size:37}, {id:62,size:38}, {id:63,size:39}, {id:64,size:40}]
[19-08-29 10:32:35:003 ICT] [{id:63,stock:17}, {id:123,stock:16}, {id:59,stock:10}, {id:64,stock:12}, {id:62,stock:14}]
//both array id value in random position but have same value
var matcharray =checkArrayForMatches(arraycode,arraysize)
function checkArrayForMatches(array,properties){
var returnArray = [];
if (Array.isArray(array[0])){
for (var i = 0,x = array.length;i<x;i++){
var row = array[i];
var match = true;
for (var j in properties){
if (properties[j] !== row[j]){
match = false;
}
}
if (match) {returnArray.push(i)};
}
} else if (typeof array[0] == 'object'){
for (var i = 0,x = array.length;i<x;i++){
var obj = array[i];
var match = true;
for (var j in properties){
if (obj[j] !== properties[j]){
match = false;
}
}
if (match) {returnArray.push(i)};
}
}
return returnArray;
}
The above function not returning any value. I would like it to returning array like this which contain size value following by stock value [{36,10}, {37,16}, {38,13}, {39,17}, {40,12}]
As you can see each returned value have a matching id.
Any help is much appreciated.
Flow:
Create a hashtable of id:stock
Use Array.map to retrieve stock from hash table using id of arraysize
Snippet:
var arraysize = [{ id: 59, size: 36}, { id: 123, size: 37}, { id: 62, size: 38}, { id: 63, size: 39}, { id: 64, size: 40}];
var arraycode = [{ id: 63, stock: 17}, { id: 123, stock: 16}, { id: 59, stock: 10}, { id: 64, stock: 12}, { id: 62, stock: 13}];
var arrayCodeObj = {};
arraycode.forEach(function(obj){arrayCodeObj[obj.id]=obj.stock});//create hash table
var arr2d = arraysize.map(function(obj){ return [obj.size, arrayCodeObj[obj.id]]})
console.log(arr2d)
console.log(arrayCodeObj)

How to Create Optional Struct with Arrays

I would like to create the following struct/array combination; however, I'm getting lost in the array nesting. Is this the proper way to set up a "City", and if so, what would be the best practice technique to modify it, so that I can init new Cities with a different customer value?
Thanks!
struct City {
var name: String
var groceryStores: [GroceryStore]
}
struct GroceryStore {
var name: String
var employeesAtInterval = [employeeIDs]
}
var employeeIDs = [40, 20, 13, 44]
Based on your code, this seems like what you wanted to achieve:
struct City {
var name: String
var groceryStores: [GroceryStore]
}
struct GroceryStore {
var name: String
// As employeeIDs are Ints, you should initialize it using this syntax
var employeesAtInterval = [Int]()
}
let employeeIDs1 = [40, 20, 13, 44]
let employeeIDs2 = [40, 20, 13, 44]
...
let groceryStore1 = GroceryStore(
name: "store 1",
employeesAtInterval: employeeIDs1
)
let groceryStore2 = GroceryStore(
name: "store 2",
employeesAtInterval: employeeIDs2
)
...
let city1 = City(name: "city 1", groceryStores: [groceryStore1, groceryStore2])
let city2 = City(name: "city 2", groceryStores: [groceryStore3, groceryStore4])
let cities = [city1, city2]

Take keys from Dictionary and map them to an array

I'm trying to build a closure that does what my title says. My code runs but it does not print what I expected.
var names: [String] = []
var namesAndAges = ["Tom": 25, "Michael": 35, "Harry": 28, "Fabien": 16]
var ofAge = namesAndAges.filter { namesAndAges in namesAndAges.value > 18 }
var addNames = ofAge.map { ofAge in names.append(ofAge.key) }
print(addNames) //this prints [(), (), ()]
Basically you are misusing filter and map methods.
Try this:
var names: [String] = []
var namesAndAges = ["Tom": 25, "Michael": 35, "Harry": 28, "Fabien": 16]
var ofAge = namesAndAges.filter { $0.value > 18 }
var addNames = ofAge.map { $0.key }
print(addNames) //this prints ["Michael", "Harry", "Tom"]
The issue you're experience is because names.append(ofAge.key) returns Void (a.k.a. the empty tuple, ()). map produces a new Array containing the return values of the given closure after it's been applied to every element of the source array (ofAge, in your example).
The names array will actually contain the data you want, but this isn't how map is meant to be used (you're essentially using it in place of forEach).
Try this instead:
var namesAndAges = ["Tom": 25, "Michael": 35, "Harry": 28, "Fabien": 16]
var namesOfAge = namesAndAges.filter { $0.value > 18 }.map{ $0.key }
print(namesOfAge)
To avoid looping more than once, this is how I do it:
var namesAndAges = ["Tom": 25, "Michael": 35, "Harry": 28, "Fabien": 16]
let addNames: [String] = namesAndAges.flatMap { $0.value > 18 ? $0.key : nil }
print(addNames) // prints ["Michael", "Harry", "Tom"]
(oh and it's shorter 🙃)

How to reverse array in Swift without using ".reverse()"?

I have array and need to reverse it without Array.reverse method, only with a for loop.
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
Swift 3:
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames : [String] = Array(names.reversed())
print(reversedNames) // ["Asus", "Lenovo", "Sony", "Microsoft", "Apple"]
Here is #Abhinav 's answer translated to Swift 2.2 :
var names: [String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [String]()
for arrayIndex in (names.count - 1).stride(through: 0, by: -1) {
reversedNames.append(names[arrayIndex])
}
Using this code shouldn't give you any errors or warnings about the use deprecated of C-style for-loops or the use of --.
Swift 3 - Current:
let names: [String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [String]()
for arrayIndex in stride(from: names.count - 1, through: 0, by: -1) {
reversedNames.append(names[arrayIndex])
}
Alternatively, you could loop through normally and subtract each time:
let names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
let totalIndices = names.count - 1 // We get this value one time instead of once per iteration.
var reversedNames = [String]()
for arrayIndex in 0...totalIndices {
reversedNames.append(names[totalIndices - arrayIndex])
}
Do you really need a for loop? If not, you can use reduce.
I guess that this is the shortest way to achieve it without reversed() method (Swift 3.0.1):
["Apple", "Microsoft", "Sony", "Lenovo", "Asus"].reduce([],{ [$1] + $0 })
Only need to make (names.count/2) passes through the array. No need to declare temporary variable, when doing the swap...it's implicit.
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
let count = names.count
for i in 0..<count/2 {
(names[i],names[count - i - 1]) = (names[count - i - 1],names[i])
}
// Yields: ["Asus", "Lenovo", "Sony", "Microsoft", "Apple"]
There's also stride to generate a reversed index:
let names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversed = [String]()
for index in (names.count - 1).stride(to: -1, by: -1) {
reversed.append(names[index])
}
It also works well with map:
let reversed = (names.count - 1).stride(to: -1, by: -1).map { names[$0] }
Note: stride starts its index at 1, not at 0, contrary to other Swift sequences.
However, to anyone reading this in the future: use .reverse() instead to actually reverse an array, it's the intended way.
var names:[String] = [ "A", "B", "C", "D", "E","F","G"]
var c = names.count - 1
var i = 0
while i < c {
swap(&names[i++],&names[c--])
}
Cristik
while i < c {
swap(&names[i],&names[c]
i += 1
c -= 1
}
Here you go:
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [String]()
for var arrayIndex = names.count - 1 ; arrayIndex >= 0 ; arrayIndex-- {
reversedNames.append(names[arrayIndex])
}
Ignoring checks for emptiness..
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [String]()
for name in names {
reversedNames.insert((name), at:0)
}
print(reversedNames)
Here is the most simpler way.
let names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [String]()
for name in names {
reversedNames.insert(name, at: 0)
}
Edited as generic
// Swap the first index with the last index.
// [1, 2, 3, 4, 5] -> pointer on one = array[0] and two = array.count - 1
// After first swap+loop increase the pointer one and decrease pointer two until
// conditional is not true.
func reverse<T>(with array: [T]) -> [T] {
var array = array
var first = 0
var last = array.count - 1
while first < last {
array.swapAt(first, last)
first += 1
last -= 1
}
return array
}
input-> [1, 2, 3, 4, 5] output ->[5, 4, 3, 2, 1]
input-> ["a", "b", "c", "d"] output->["d", "c", "b", "a"]
// Or a shorter version divide and conquer
func reversed<T>(with arr: [T]) -> [T] {
var arr = arr
(0..<arr.count / 2).forEach { i in
arr.swapAt(i, arr.count - i - 1)
}
return arr
}
The most efficient way is to swap the items at start- and endIndex and move the indices bidirectional to the middle. This is a generic version
extension Array {
mutating func upsideDown() {
if isEmpty { return }
var 👉 = startIndex
var 👈 = index(before: endIndex)
while 👉 < 👈 {
swapAt(👉, 👈)
formIndex(after: &👉)
formIndex(before: &👈)
}
}
}
Like this, maybe:
names = names.enumerate().map() { ($0.index, $0.element) }.sort() { $0.0 > $1.0 }.map() { $0.1 }
Oh, wait.. I have to use for loop, right? Then like this probably:
for (index, name) in names.enumerate().map({($0.index, $0.element)}).sort({$0.0 > $1.0}).map({$0.1}).enumerate() {
names[index] = name
}
Swift 5:
let names: [String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversenames: [String] = []
let count = names.count
for index in 0..<count {
reversenames.insert(names[count-index-1], at: index)
}
print(reversenames)
This will work with any sized array.
import Cocoa
var names:[String] = [ "A", "B", "C", "D", "E","F"]
var c = names.count - 1
for i in 0...(c/2-1) { swap(&names[i],&names[c-i]) }
print(names)
Here is how I did it and there is no warning for Swift 3
let names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [String]()
for name in names.enumerate() {
let newIndex = names.count - 1 - name.index
reversedNames.append(names[newIndex])
}
or just simply
reversedNames = names.reverse()
Here the code for swift 3
let array = ["IOS A", "IOS B", "IOS C"]
for item in array.reversed() {
print("Found \(item)")
}
func reverse(array: inout [String]) {
if array.isEmpty { return }
var f = array.startIndex
var l = array.index(before: array.endIndex)
while f < l {
swap(array: &array, f, l)
array.formIndex(after: &f)
array.formIndex(before: &l)
}
}
private func swap( array: inout [String], _ i: Int, _ j: Int) {
guard i != j else { return }
let tmp = array[i]
array[i] = array[j]
array[j] = tmp
}
Or you can write extension of course
var rArray : [Int] = [2,5,6,8,3,8,9,10]
var ReArray = [Int]()
var a : Int = 1
func reversed (_ array: [Int]) -> [Int] {
for i in array {
ReArray.append(array[array.count-a])
a += 1
}
rArray = ReArray
return rArray
}
reversed(rArray)
print(rArray)
var arr = [1, 2, 3, 4, 5] // Array we want to reverse
var reverse: [Int]! // Array where we store reversed values
reverse = arr
for i in 0...(arr.count - 1) {
reverse[i] = arr.last! // Adding last value of original array at reverse[0]
arr.removeLast() // removing last value & repeating above step.
}
print("Reverse : \(reverse!)")
A more simple way :)
Recently I had an interview and I was asked this question, how to reverse an array without using reversed(). Here is my solution below:
func reverseArray( givenArray:inout [Int]) -> [Int] {
var reversedArray = [Int]()
while givenArray.count > 0 {
reversedArray.append(givenArray.removeLast())
}
return reversedArray
}
var array = [1,2,3,4,5,6,7]
var reversed = reverseArray(givenArray: &array)
First, need to find the middle of array. This method is faster than the linear time O(n) and slower than the constant time O(1) complexity.
func reverse<T>(items: [T]) -> [T] {
var reversed = items
let count = items.count
let middle = count / 2
for i in stride(from: 0, to: middle, by: 1) {
let first = items[i]
let last = items[count - 1 - i]
reversed[i] = last
reversed[count - 1 - i] = first
}
return reversed
}
Do it like this for reversed sorting.
let unsortedArray: [String] = ["X", "B", "M", "P", "Z"]
// reverse sorting
let reversedArray = unsortedArray.sorted() {$0 > $1}
print(reversedArray) // ["Z", "X", "P", "M", "B"]
I like simple codes.
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [""]
for name in names {
reversedNames.insert(name, at: 0)
}
print(reversedNames)
var names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
// 'while' loop
var index = 0
let totalIndices = names.count - 1
while index < names.count / 2 {
names.swapAt(index, totalIndices-index)
index += 1
}
// 'for' loop
for index in 0..<names.count/2 {
names.swapAt(index, names.count-index-1)
}
// output: "["Asus", "Lenovo", "Sony", "Microsoft", "Apple"]"
You can use the swift3 document:
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let reversedNames = names.sorted(by: >)
// reversedNames is equal to:
// ["Ewa", "Daniella", "Chris", "Barry", "Alex"]

Convert String Array into Int Array Swift 2?

[Xcode 7.1, iOS 9.1]
I have an array: var array: [String] = ["11", "43", "26", "11", "45", "40"]
I want to convert that (each index) into an Int so I can use it to countdown from a timer, respective of the index.
How can I convert a String array into an Int Array in Swift 2?
I've tried several links, none have worked and all of them have given me an error. Most of the code from the links is depreciated or hasn't been updated to swift 2, such as the toInt() method.
Use the map function
let array = ["11", "43", "26", "11", "45", "40"]
let intArray = array.map { Int($0)!} // [11, 43, 26, 11, 45, 40]
Within a class like UIViewController use
let array = ["11", "43", "26", "11", "45", "40"]
var intArray = Array<Int>!
override func viewDidLoad() {
super.viewDidLoad()
intArray = array.map { Int($0)!} // [11, 43, 26, 11, 45, 40]
}
If the array contains different types you can use flatMap (Swift 2) or compactMap (Swift 4.1+) to consider only the items which can be converted to Int
let array = ["11", "43", "26", "Foo", "11", "45", "40"]
let intArray = array.compactMap { Int($0) } // [11, 43, 26, 11, 45, 40]
Swift 4, 5:
Use compactMap with cast to Int, solution without '!'.
let array = ["1","foo","0","bar","100"]
let arrayInt = array.compactMap { Int($0) }
print(arrayInt)
// [1, 0, 100]
Swift 4, 5:
The instant way if you want to convert string numbers into arrays of type int (in a particular case i've ever experienced):
let pinString = "123456"
let pin = pinString.map { Int(String($0))! }
And for your question is:
let pinArrayString = ["1","2","3","4","5","6"]
let pinArrayInt = pinArrayString.map { Int($0)! }
i suggest a little bit different approach
let stringarr = ["1","foo","0","bar","100"]
let res = stringarr.map{ Int($0) }.enumerate().flatMap { (i,j) -> (Int,String,Int)? in
guard let value = j else {
return nil
}
return (i, stringarr[i],value)
}
// now i have an access to (index in orig [String], String, Int) without any optionals and / or default values
print(res)
// [(0, "1", 1), (2, "0", 0), (4, "100", 100)]
A slightly different example
let digitNames = [0: "Zero", 1: "One", 2:"Two", 3: "Three",
4:"Four",5:"Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 10:"Ten"
]
let numbers = [16,58,510]
let strings = numbers.map { (number) -> String in
var number = number
var output = ""
repeat {
output = digitNames[number % 10]! + output
number /= 10
} while number > 0
return (output)
}
print(strings)
// strings is inferred to be of type [String]
// its value is ["OneSix", "FiveEight", "FiveOneZero"]

Resources