Foundation (Software Framework) Reference

Kip Landergren

(Updated: )

My cheat sheet for Foundation covering NSExpression, format strings, and other resources.

Contents

NSExpression

An NSExpression represents a function. It’s goal is to represent the structure of a calculation, take any supplied arguments, and evaluate them together into a single output value.

Predefined Functions

Important points:

Example. Single parameter input:

let ints = [2, 3, 5, 7, 11, 13, 17, 19, 23]
let numericsExp = NSExpression(forConstantValue: ints)
NSExpression(forFunction: "average:", arguments: [numericsExp]) // Double
NSExpression(forFunction: "count:", arguments: [numericsExp]) // Int
NSExpression(forFunction: "max:", arguments: [numericsExp]) // passed Type
NSExpression(forFunction: "median:", arguments: [numericsExp]) // passed Type
NSExpression(forFunction: "min:", arguments: [numericsExp]) // passed Type
NSExpression(forFunction: "mode:", arguments: [numericsExp]) //[passed Type]
NSExpression(forFunction: "stddev:", arguments: [numericsExp]) // Double
NSExpression(forFunction: "sum:", arguments: [numericsExp]) // passed Type

Example. Evaluating expressions for their value:

let rawData = [2, 3, 5, 7, 11, 13, 17, 19, 23]
let rawDataExp = NSExpression(forConstantValue: rawData)
let sumExp = NSExpression(forFunction: "sum:", arguments: [rawDataExp])
print(sumExp.expressionValue(with: nil, context: nil) as! Int) // 100

Example. Using predefined functions with placeholder variables, passing in data via expressionValue(with:context:):

let rawData = [2, 3, 5, 7, 11, 13, 17, 19, 23]
let sumExpPlaceholder = NSExpression(format: "sum:(ARGS)")
print(sumExpPlaceholder.expressionValue(with: ["ARGS":rawData], context: nil) as! Int) // 100

Full list of predefined functions.

Use In Core Data

Refer to Core Data Reference

Format Strings

%d signed 32-bit integer
%@ object

More info in this Stack Overflow question: “What are the supported Swift String format specifiers?”.

Unicode Date Format Patterns

Based on tr35-31:

y Year. e.g. “AD 2020” becomes “2020”
yy Year, maximum length of 2. e.g. “AD 2020” becomes “20”
yyy Year, with up to 2 spaces of padding. e.g. “AD 20” becomes “020”
yyyy Year, with up to 3 spaces of padding. e.g. “AD 20” becomes “0020”
yyyyy Year, with up to 4 spaces of padding. e.g. “AD 2020” becomes “02020”
M Month, numerical. e.g. “April” becomes “4”
MM Month, numerical, with zero padding. e.g. “April” becomes “04”
MMM Month, abbreviation. e.g. “April” becomes “Apr”
MMMM Month, full name. e.g. “April” becomes “April”
MMMMM Month, narrow name. e.g. “April” becomes “A”

Note: I have yet to determine whether Unicode Date Format Patterns is independent of, or an extension of, ISO 8601 date format patterns.

Locale

Get a user’s current locale:

Locale.current

Documentation