Hi! While programming in Swift I have accumulated many code snippets. Some of them are mine and some of them come from the internet. Here I'm sharing 5 tiny quality-of-life snippets. Hopefully you will find them useful.
This snippet adds a window variable to NSViewController. It requires the window to exist (eg. be in NSApp.windows, in most cases that will be true) and that there is only one window with the specified view controller. It will return the window with the view controller on which it is called.
This is a simple wrapper around FileManager.fileExists()
as an extension to FileManager
that checks whether a path provided as a string leads to a directory.
This snippet adds a subscript to arrays. It checks whether index is within the array's range then returns an element or nil depending on the check. You can use it like this:
This might save you few lines of code for checking and force you to handle the edge case without crashing the app.
This pretty lengthy snippet adds a simple SwiftUI wrapper around WKWebView
(which needs to be imported). It only requires a binding to a url, which will be loaded. In more complex cases, you can pass onLoadStart
and onLoadFinish
handlers which will run when the web view starts and finishes loading and a WKWebView
class instance. Since in Swift classes are passed by reference, you can use this instance in your view to control the web view (go back, forward, etc).
Once again, a wrapper. It wraps NSAlert
in one function so that you don't need to rewrite this code. It accepts a message and informative text which will be used on the alert. It also optionally accepts a list of button titles which will be added to the alert. It also runs asynchronously on the main thread, so it works even when run in another thread. Here I'd like to add that you can use NSAlert.accessoryView
to create alerts with custom views, for example I did something like this:
which creates an alert with a pop up button for selecting a value.
As a sidenote, if you are dealing with many snippets of various types (like these ones), CodeMenu can help you organize, access and use their full potential.