What is the shortest way to run same code n times in Swift?
Sticking with a for
loop - you could extend Int
to conform to SequenceType
to be able to write:
for i in 5 { /* Repeated five times */ }
To make Int
conform to SequenceType
you'll could do the following:
extension Int : SequenceType {
public func generate() -> RangeGenerator<Int> {
return (0..<self).generate()
}
}
Running Swift code in while loop but times out
If you run this code on a free online platform (like iswift.org/playground), your program will time out because it would run forever otherwise.
To counter this problem limit your loop so it only does, for example, 1000 cycles.
View the example online: http://swift.sandbox.bluemix.net/#/repl/59123b184ee0cd258050b2cd
var coolingDown = false
var blasterFireCount = 0
var temp = 0
for _ in 0..<1000 {
if coolingDown {
temp -= 1
print("cooling down \(temp)")
if temp == 0 { coolingDown = false }
} else {
temp += 1
blasterFireCount += 1
print("fire \(blasterFireCount)")
if temp == 100 { coolingDown = true }
}
}
How to create multiple delays using a dispatch queue?
// Code I want to run every 1 second for 20 times
What you're looking for is a Timer.
https://developer.apple.com/documentation/foundation/timer
var timer : Timer?
var times = 0
@objc func fired(_ t:Timer) {
times += 1
print("do your code") // do your code here
if times == 20 {
t.invalidate()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self,
selector: #selector(fired), userInfo: nil,
repeats: true)
}
You will see that print("do your code")
runs every 1 second 20 times.
Swift -How does a for loop finish before the line under it?
Fundamentally all operations are executed sequentially as stated in Oleg's answer.
What you have to understand is that special things like for loop
statements or if statements
or other, are sort of instructions for the runtime. And when the code executtion gets to the point where it encounters for loop
instruction it goes on and on inside of a for loop. It just knows that this thing inside of for loop {}
should be executed n
times before it can continue. So when the for loop finishes, it goes to the next line of code and does whatever instruction is there.
This is not very deep explanation, but I was trying to be simplistic. Hope it helps.
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.
How the time complexity is calculated for a loop - Swift
The two loops have the same time complexity - O(1) constant time, because they will always run 100 times. Nothing about them
As you may know time complexity measures how the time needed for an algorithm to run changes as a variable changes. For example, this loop has time complexity O(n):
for i in 0..<n {
print(i)
}
As n
increases, the time needed to run that loop increases linearly, hence O(n).
This loop would be O(n^2):
for i in 0..<(n*n) {
print(i)
}
This loop would be O(log(n)):
for i in 0..<Int(log(n)) {
print(i)
}
(Obviously there are other ways of making O(n^2) and O(log(n)) loops)
I think the loops you are given are just supposed to illustrate different time complexities by plotting a "graph" of the time needed increases as n increases. As you can see from the screenshot, the O(log(n)) loop plots a log(n) graph.
Related Topics
Swift Decodable, Endpoint Returns Completely Different Types
Moving an Object Across the Screen at a Certain Speed.(Sprite Kit)
Tabview, Tabitem: Running Code on Selection or Adding an Ontapgesture
Value of Type 'Authdataresult' Has No Member 'Uid'
Don't Delete Some Rows from Uitableview
How to Get Exactly the Same Point on Different Screen Sizes
Get Element from Array of Dictionaries According to Key
My Button Is Centered for iPhone 6 and 6 Plus, But Not for iPhone 5
How to Get Video Duration Fro Avasset in Swift
Array Search Function Not Working in Swift
How to Use Dispatchgroup/Gcd to Execute Functions Sequentially in Swift
Xcode 8.0 Cbcentralmanager Issue
Arkit Setting Worldtrackingconfiguration to Gravityandheading Produces Error