Skip to content

Instantly share code, notes, and snippets.

@wildthink
Created June 27, 2024 22:02
Show Gist options
  • Save wildthink/001fa394a8ae9f1bc40a5c5712973b12 to your computer and use it in GitHub Desktop.
Save wildthink/001fa394a8ae9f1bc40a5c5712973b12 to your computer and use it in GitHub Desktop.
The APIKeys makes it easy to provide an optional secretAPIKeys.swift file in your project wherein the secret values are provided.
//
// APIKeys.swift
//
// Created by Jason Jobe on 6/18/24.
//
import Foundation
/**
The APIKeys makes it easy to provide an optional \_secretAPIKeys.swift
file in your project wherein the secret values are provided.
As an example, you can define your own keys easily by relying on the `#function`
to provide a string key ("myAPIKey" in this case) that is used to look up the value
in the dictionary of shared keys.
```
static var myAPIKey: String {
shared.keys[#function] ?? "DEFAULT_API_VALUE"
}
```
It is recommended that the file containing the actual secrets be correspondingly
named "secretAPIKeys.swift" and that it be added to your .gitignore.
To be more secure, ignore all 'secret' files.
In the the "secretAPIKeys.swift" file insert the following:
```
extension APIKeys {
func load(_ key: Int = 0) -> [String:String] {
[
"myAPIKey": "YOUR_REAL_KEY",
]
}
}
```
NOTE: the different load function signatures. This is required for the
call in the init to pick up the correct values.
*/
public struct APIKeys {
static var shared: APIKeys = .init()
private(set) var values: [String:String] = [:]
init() {
values = load()
}
}
// MARK:
public extension APIKeys {
/**
An example (or not) of how to define your own keys easily.
```
static var yelpAPIKey: String {
shared.keys[#function] ?? "DEFAULT_API_VALUE"
}
```
*/
static var yelpAPIKey: String {
shared.values[#function] ?? "DEFAULT_API_VALUE"
}
}
extension APIKeys {
/**
This disfavoredOverload is here to keep your project buildable even when the
\_secretsAPIKeys are not included.
*/
@_disfavoredOverload
func load(_ key: String = "") -> [String:String] {
[:]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment