Code screenshots

Swift Tips 007 by John Sundell

A small note

What does this code say

This code extends UserDefaults and adds a calculated property named onboardingCompleted of type BOOL to get the value in UserDefaults with the key named onboardingCompleted

#functionWhat is the

#function is a compilation symbol provided by the Swift compiler to describe the name of the method that contains this symbol.

symbol type describe
#file String Path to the file containing the symbol
#line Int The line number where the symbol appears
#column Int The column where the symbol appears
#function String The name of the method that contains the symbol

Before Swift 3.0, #function was written __FUNCTION__

How do I use these compiler symbols?

It is easy to think of these compiled symbols as variables, so use them the way you use variables.

The code screenshot shows how to use compiled symbols in a method definition, while the following code shows how to use compiled symbols in a method definition.

Suppose we want to print out information about a method, such as the name of the file in which it is located, the name of the caller, the current number of lines, and so on.

func printLog<T>(message: T, file: String = #file, method: String = #function, line: Int = #line)
{
    print("\((file as NSString).lastPathComponent)[\(line)].\(method): \(message)")}Copy the code

So its output would look something like this

// Test.swift
func method(a) {
    / /...
    printLog("This is an output.")
    / /...
}

/ / output:
// test.swift [62], method(): this is an output
Copy the code

What are the benefits of this

Before we get to the benefits, let’s think about how we can get keys out of UserDefaults if we don’t use #function. Chances are your code will look something like this:

extension UserDefaults {
    var onboardingCompleted: Bool {
        get { return bool(forKey:"onboardingCompleted")}set { set(newValue, forKey: "onboardingCompleted")}}}Copy the code

In this case, we have to manually ensure that the key values in the getter and setter are the same, which increases the probability of errors.

By using #function as the key in the picture, we’re pretty good at matching the key in the getter and setter. We just care if the method name is the key we need.