For Loop Cycle Showing Always the Last Array Value Swift 3 After Http Request

Swift how can i check if i iterate through the last item of List[String]

The answer of dr_barto will work but needs the following adaptation:

    for (idx, element) in array.enumerated() {
if idx == array.endIndex-1 {
// handling the last element
}
}

From the Apple documentation:

endIndex is the array’s “past the end” position—that is, the position one greater than the last valid subscript argument

Swift 3 : How to use for loop for looping arrays

For that you need to simply maintain the index of the current element for array object.

var currentIndex = 0

@IBAction func buttonClick(_ sender: UIButton) {
print(array[currentIndex])
currentIndex += 1
if currentIndex == array.count {
currentIndex = 0
}
}

Wait until swift for loop with asynchronous network requests finishes executing

You can use dispatch groups to fire an asynchronous callback when all your requests finish.

Here's an example using dispatch groups to execute a callback asynchronously when multiple networking requests have all finished.

override func viewDidLoad() {
super.viewDidLoad()

let myGroup = DispatchGroup()

for i in 0 ..< 5 {
myGroup.enter()

Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON { response in
print("Finished request \(i)")
myGroup.leave()
}
}

myGroup.notify(queue: .main) {
print("Finished all requests.")
}
}

Output

Finished request 1
Finished request 0
Finished request 2
Finished request 3
Finished request 4
Finished all requests.

Swift Append() method overwrite previous data

RequestItem is reference type and you are using always the (reference to the) same item.

Create a new instance inside the loop

var requestItems: [RequestItem] = []

func setUpData() {
for i in 1...10 {
if i < 3 {
let requestItem = RequestItem()
requestItem.itemId = i as NSNumber
requestItem.requestedQty = 10
requestItem.name = "Item name \(i)"

self.requestItems.append(requestItem)

print("--------------------------------------------Start--------------------------------------------")
print( requestItems )
print("--------------------------------------------End--------------------------------------------")
}
}
}

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)

How can I run through three separate arrays in the same for loop?

If you are always sure the arrays will be equal in length, then you are better to just loop through one of the arrays and use it's index to reference the others:

for (index, name) in enumerate(Name) {
makeUser(name, userAge: Age[index], userGender: Gender[index])
}

However, I would recommend getting this data into a dictionary, but I assume this is just sample data to illustrate a point. :)

Iterate through Swift array and change values

I found a simple way and would like to share it.

The key is the definition of myArray. It would success if it's in this way:

 let myArray : [NSMutableDictionary] = [["firstDict":1, "otherKey":1], ["secondDict":2, "otherKey":1], ["lastDict":2, "otherKey":1]]

myArray.enumerated().forEach{$0.element["index"] = $0.offset}

print(myArray)






[{
firstDict = 1;
index = 0;
otherKey = 1;
}, {
index = 1;
otherKey = 1;
secondDict = 2;
}, {
index = 2;
lastDict = 2;
otherKey = 1;
}]

Array add previous index value to next index Swift 3

You can accomplish this by using a var total to keep track of the running total and use map to create a new array with each item replaced by total of it and the previous ones:

let array = [100.0, 10.0, 250.0]
var total = 0.0

let result = array.map { value -> Double in total += value; return total }
print(result)
[100.0, 110.0, 360.0]

Using a for loop:

This accomplishes the same task using a for loop to build up the result:

let array = [100.0, 10.0, 250.0]
var result = [Double]()
var total = 0.0

for value in array {
total += value
result.append(total)
}

print(result)
[100.0, 110.0, 360.0]

Return String of for loop - Swift 3

The dataTask is an async task. So this function always returns the stonesNew immediately before the dataTask is completed. So the solution for an async task is completionHanlder, like this:

static func getStones(completion: @escaping (Double) -> Void)  {
let url = NSURL(string: "MYURL")
let request = NSMutableURLRequest(url: url as URL!)
var stonesNew = Double()
let task = URLSession.shared.dataTask(with: request as URLRequest) {data,response,error in

let responseString = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary
let contacts = responseString["Sheet1"] as? [AnyObject]

for contact in contacts!{

let stones = contact["stones"] as! Double
stonesNew = stones
}

completion(stonesNew)
}
task.resume()
}

And use it like this:

MyClass.getStones(completion: { (stones) in    
print(stones)
})


Related Topics



Leave a reply



Submit