Simple Neural Network Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Simple Neural Network runs in O(n*w) time and O(w) space, in Swift as in every other language.
- ✓No Gaussian sampler ships in the standard library either, but Double.random(in:using:) gives seedable uniform sampling once you supply your own RandomNumberGenerator conformance; the DEFAULT generator, SystemRandomNumberGenerator, is cryptographically seeded from the OS and deliberately not reproducible run to run, so reproducibility requires writing a custom generator, and a Gaussian sampler still means hand-rolling Box-Muller on top of whichever uniform source you use.
- ✓Define struct Layer { var weights: [Double]; var biases: [Double]; let inSize, outSize: Int } as a value type, and thread a custom RandomNumberGenerator through the initializer as an inout parameter rather than a class reference.
- ✓The Swift trap: Because Layer is a struct, an array of layers, var network: [Layer], has copy-on-write value semantics one level up too.
- ✓SystemRandomNumberGenerator, the default behind plain Double.random(in:), is cryptographically strong, which costs measurably more per call than a small deterministic generator like a splitmix64 or xorshift variant.
What Simple Neural Network actually is
Simple Neural Network in Swift: what you actually reach for
Swift implementation
import Foundation
protocol SeededGenerator: RandomNumberGenerator {}
struct SplitMix64: SeededGenerator {
private var state: UInt64
init(seed: UInt64) { state = seed }
mutating func next() -> UInt64 {
state &+= 0x9E3779B97F4A7C15
var z = state
z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B9
z = (z ^ (z >> 27)) &* 0x94D049BB133111EB
return z ^ (z >> 31)
}
}
func gaussian<G: RandomNumberGenerator>(using rng: inout G) -> Double {
let u = Double.random(in: 0.0001...1, using: &rng) // avoid log(0)
let v = Double.random(in: 0...1, using: &rng)
return (-2 * Foundation.log(u)).squareRoot() * cos(2 * .pi * v)
}
struct Layer {
var weights: [Double]
var biases: [Double]
let inSize, outSize: Int
}
func makeLayer<G: RandomNumberGenerator>(inSize: Int, outSize: Int, rng: inout G) -> Layer {
let scale = (2.0 / Double(inSize)).squareRoot() // He init
var weights = [Double](repeating: 0, count: inSize * outSize)
for i in 0..<weights.count { weights[i] = gaussian(using: &rng) * scale }
return Layer(weights: weights, biases: [Double](repeating: 0, count: outSize), inSize: inSize, outSize: outSize)
}
var rng = SplitMix64(seed: 42)
let layer = makeLayer(inSize: 784, outSize: 128, rng: &rng)Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(n*w)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Simple Neural Network?
No Gaussian sampler ships in the standard library either, but Double.random(in:using:) gives seedable uniform sampling once you supply your own RandomNumberGenerator conformance; the DEFAULT generator, SystemRandomNumberGenerator, is cryptographically seeded from the OS and deliberately not reproducible run to run, so reproducibility requires writing a custom generator, and a Gaussian sampler still means hand-rolling Box-Muller on top of whichever uniform source you use.
What is the most common Swift mistake when implementing Simple Neural Network?
Because Layer is a struct, an array of layers, var network: [Layer], has copy-on-write value semantics one level up too. Passing network into a helper closure that captured it BY VALUE before a loop began, instead of by inout, lets that closure mutate its own private copy silently; the outer network the training loop continues from is never touched, both copies remain individually valid the whole time, and no runtime error surfaces anywhere.
How does Simple Neural Network actually perform in Swift?
SystemRandomNumberGenerator, the default behind plain Double.random(in:), is cryptographically strong, which costs measurably more per call than a small deterministic generator like a splitmix64 or xorshift variant. Sampling millions of initialization values through the system generator has a real, avoidable cost that a hand-written RandomNumberGenerator conformance, a few lines of code, removes entirely, on top of the reproducibility it buys. Time complexity is O(n*w) and space is O(w).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialWant to try this with a model on your own laptop? Local AI setup guides for Ollama and LM Studio are on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.