Hello,
How can I do "import Cocoa" on windows?
If there is no official way is there a different way ?
I need to use the sleep function
Hello,
How can I do "import Cocoa" on windows?
If there is no official way is there a different way ?
I need to use the sleep function
Cocoa (AppKit
) is macOS-only, but the standard library and Foundation
are available elsewhere -- and that includes Task.sleep(nanoseconds:)
. Do you need a different sleep function?
Can I import foundation ?
Yes, if you set everything up correctly, import Foundation
should work.
error: 'async' call in a function that does not support concurrency
Task.sleep(nanoseconds: 5000)
you need to mark the function it’s in as being async
. this means adding the keyword async
before the function’s return type.
so can you give an example
- static func main() throws
+ static func main() async throws
{
try await Task.sleep(nanoseconds: 5000)
}
I dont have a function
You have two options for sleeping:
In a Swift async context, use Task.sleep(nanoseconds:)
or one of its variants. These are built-in.
Outside of that context, use Thread.sleep(forTimeInterval:)
or one of its variants. To access these, import Foundation.
The Thread
option blocks the thread in the traditional way. On Unix-y systems it might be implemented by nanosleep
, for example.
The Task
option is tied to Swift concurrency. That’s too complex to explain here but there are lots of good resources other there. To start, I recommend the Concurrency chapter in TSPL.
Share and Enjoy
Quinn “The Eskimo!” @ DTS @ Apple
Also, you can call the Windows Sleep function by importing WinSDK.
#if os(Windows)
import WinSDK
#endif
func msleep(milliseconds: UInt32) {
#if os(Windows)
WinSDK.Sleep(milliseconds)
#else
usleep(milliseconds * 1000)
#endif
}