PadCodedocs

Formulas for Swift developers

PadCode's formulas are Swift-style expressions that fill in real SwiftUI views. What carries over from Swift, what's different, and the formula function for each Swift method you'd reach for.

Every component in PadCode is a real SwiftUI view: a Text is SwiftUI's Text, a Column is a VStack, a Switch is a Toggle. PadCode draws them from your app's data, without compiling any code. The values that change go in formulas: short expressions, written much like Swift, that PadCode works out as your app runs.

If you know Swift, you can read formulas already. This page is what's the same, what isn't, and the function to use for each Swift method you'd reach for. For everything formulas can do, see the formula language reference and every function.

#A formula is one expression

A formula is a single expression, like the right-hand side of a Swift let: total * (1 + tip) / people. It has no statements, no let or var, no closures and no control flow. What would be statements in Swift are actions in PadCode: Set Value for an assignment, If for an if, Repeat for Each for a for loop. Formulas fill in their settings.

#What's the same as Swift

SwiftIn a formula
+ - * /, and % for the remainderThe same, with the same precedence
== != < <= > >=The same
&&, ||, !The same
condition ? a : bThe same
optional ?? fallbackThe same (but see the precedence note below)
"text""text" or 'text'
[1, 2, 3]The same
user.name, list[0], record["key"]The same
-x, parenthesesThe same

#What's different

In SwiftIn a formula
Int, Double, CGFloat…One kind of number: 7 / 2 is 3.5, and % works with decimals.
"Total: \(total)"No interpolation inside a formula: join with +, as in 'Total: ' + total. In a text setting, braces do it: Total: {total}. See Text with values.
"a" + 1 is an error+ joins text with anything: 'Item ' + 1 is "Item 1".
user?.address?.cityNo ?.: user.address.city is already safe, and is null when any part is missing.
nilnull.
a ?? 0 > 5 means a ?? (0 > 5)……and in a formula too, because ?? is looser than comparisons. Write (a ?? 0) > 5.
1 < 2 < 3 doesn't compileIt's read as (1 < 2) < 3, which compares true with 3: an error. Use &&.
if x needs a Bool!, &&, || and conditions take any value, and decide what counts as true: 0, '', [] and null are false.
sin(.pi / 2)Angles are in degrees: sin(90) is 1.
name.count, name.uppercased()No methods or properties of your own values: use free functions, like count(name) and uppercase(name). The table below has them all.
{ $0.done }No closures: list functions take a formula with it as each item, like filter(todos, !it.done).
struct, Dictionary(…)No new records in a formula: a record comes from a variable, an API's answer, or parseJSON('{"a": 1}').

#Swift methods and their functions

#Numbers

SwiftFormula
x.rounded(), (x * 100).rounded() / 100round(x), round(x, 2)
floor(x), ceil(x), abs(x)floor(x), ceil(x), abs(x)
min(a, b), max(a, b)min(a, b), max(a, b), with any number of values
min(max(x, lo), hi)clamp(x, lo, hi)
sqrt(x), pow(x, y)sqrt(x), power(x, y)
Int.random(in: 1...6)random(1, 6) (both ends included)
Double.pipi()
log10(x), log2(x), log(x) (natural)log(x) (base 10 unless you give one), log(x, 2), log(x, exp(1))
exp(x)exp(x)

#Text

SwiftFormula
s.count, s.isEmptycount(s), isEmpty(s)
s.uppercased(), s.lowercased(), s.capitalizeduppercase(s), lowercase(s), capitalize(s)
s.trimmingCharacters(in: .whitespaces)trim(s)
s.contains("x"), s.hasPrefix("x"), s.hasSuffix("x")contains(s, 'x'), startsWith(s, 'x'), endsWith(s, 'x')
String(s.prefix(3)), String(s.dropFirst(2))slice(s, 0, 3), slice(s, 2)
s.replacingOccurrences(of: "a", with: "b")replace(s, 'a', 'b')
s.components(separatedBy: ",")split(s, ',')
String(s.reversed())reverse(s)
String(repeating: s, count: 3)repeat(s, 3)
s.range(of: pattern, options: .regularExpression) != nilmatches(s, pattern)
s.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)urlEncode(s)
Double(s)number(s)
String(describing: x)text(x)

#Formatting

SwiftFormula
x.formatted(.currency(code: "USD"))currency(x), or currency(x, 'USD')
x.formatted(.percent)percent(x), percent(x, 1)
String(format: "%.2f", x)fixed(x, 2)
x.formatted(.number.notation(.compactName))compactNumber(x) (1.2K)
"\(n) item\(n == 1 ? "" : "s")"plural(n, 'item')
String(format: "%02d", n)padStart(n, 2, '0') ("05")
date.formatted(date: .abbreviated, time: .omitted)formatDate(date), with a style

#Dates

SwiftFormula
Date()now()
Calendar.current.startOfDay(for: Date())today(), or startOf(date, 'day')
date.addingTimeInterval(60 * m)addMinutes(date, m)
Calendar.current.date(byAdding: .day, value: n, to: date)addDays(date, n), addMonths(date, n)
Calendar.current.dateComponents([.day], from: a, to: b).daydaysBetween(a, b), and hoursBetween, monthsBetween and the rest
Calendar.current.component(.hour, from: date)hour(date), day(date), weekday(date) and the rest
ISO8601DateFormatter().date(from: s)date(s)
date.timeIntervalSince1970timestamp(date)

#Lists

SwiftFormula
list.count, list.isEmptycount(list), isEmpty(list)
list.first, list.lastfirst(list), last(list)
list.filter { !$0.done }filter(list, !it.done)
list.first(where: { $0.id == id })find(list, it.id == id)
list.contains(where: { $0.late })any(list, it.late)
list.allSatisfy { $0.done }all(list, it.done)
list.map { $0.price * $0.qty }map(list, it.price * it.qty)
list.sorted { $0.date < $1.date }sort(list, it.date), and sort(list, it.date, true) for newest first
list.reduce(0, +)sum(list), and average(list), median(list)
list.contains(x), list.firstIndex(of: x)contains(list, x), indexOf(list, x)
list + [item], a + bappend(list, item), concat(a, b)
Array(list[1..<3])slice(list, 1, 3)
Array(Set(list)) (keeping order)unique(list)
list.reversed(), list.shuffled()reverse(list), shuffle(list)
list.joined(separator: ", ")join(list, ', ')
Array(1...5)range(1, 5) (both ends included)
dict.keys, dict.valueskeys(record), values(record)

#Everything else

SwiftFormula
UUID().uuidStringuuid()
type(of: x)typeOf(x)
JSONSerialization.jsonObject(with:)parseJSON(text)
JSONEncoder().encode(x)toJSON(x)
Color(red: r / 255, green: g / 255, blue: b / 255)rgb(r, g, b), giving hex text like "#5B6CFF"
Color.mix(…)mix(color, otherColor, 0.5)

#Where formulas go

  • A setting's ⚡︎ button → Formula… links any setting to one. The setting shows the formula after ƒ.
  • Text with braces: Hello, {name}! and Total: {currency(total)}.
  • Steps' settings, like Set Value's new value or If's condition.
  • Describe it, on Pro, writes one from your words. See Writing a formula from words.

#See also