Swift
Learn Swift by typing safe, idiomatic code.
Type your way through Swift: optionals and optional binding, closures, protocols and protocol extensions, enums with associated values, and value-type structs. Every snippet is idiomatic Swift, and an AI tutor explains each line — how optional chaining stays safe, why protocol-oriented design beats subclassing — so the language's safety model sticks while you build speed.
Progress0 / 682 solved · 0/50 sections
best wpm
0
avg wpm
0
accuracy
0%
runs
0
level
1
rating
1000
Run Swift on your machine
1. Install the toolchain
xcode-select --install # macOS, or see swift.org2. Save your code as hello.swift, then compile & run
swift hello.swiftprogress by section
1Fundamentals0/8start →
2Strings In Depth0/18start →
3Values & References0/16start →
Classes share on assignStructs copy on assignValue vs reference typesArrays are value typesA class arg is sharedEnums are value typesIdentity with ===inout parametersSwap with inoutlet makes a struct constantA struct arg is a copylet on a class binds the referenceMutating methodsARC and deinitShared ownershipweak breaks a cycle
4Slices & Arrays0/17Unlock →
5Data structures0/9Unlock →
6Iterators0/20Unlock →
7Traits0/20Unlock →
EquatableDefining a protocolComparable & sortingCustomStringConvertibleProtocol extension defaultHashableOperator: +Operator: unary -RawRepresentable enumProtocol compositionMutating requirementOperator: +=Operator: * by scalarStatic requirementConstrained associated typeAssociated typeCustom iteratorSubscriptExpressibleByArrayLiteralConditional conformance
8Generics0/20Unlock →
Trait constraintGeneric enumGeneric functionGeneric structTwo type parametersProtocol compositionConstrained extensionProtocol-required initGeneric higher-order transformGeneric methodsGeneric minNewtype wrapperOpaque return type (some)Generic over SequenceGeneric over iterableswhere clauseAssociated typesGeneric with a closure paramStatic vs dynamic dispatchPhantom type
9Lifetimes0/20Unlock →
defer for cleanupProgram-long lifetimeValue semanticsARC frees on last releaseCapture by valuedefer with early returndefer runs in reverseguard-let binding scopeTwo strong referencesValues avoid cyclesChaining on a weak refScope ends the lifetimeUnowned referenceWeak referenceweak is always optionalBreak a cycle with weakA weak delegateA retain cycle[unowned self] in a closure[weak self] in a closure
10Closures0/20Unlock →
A closureShorthand argument namesCapturing the environmentExplicit types & block bodyTrailing closureCallbacksCapture list (value snapshot)Function referencesClosures drive iteratorsMutating a captured variableClosure as a parametersorted(by:) with a closureCurrying@escapingReturning a closureArray of closuresHigher-order: composeReturn different closures[unowned self] capture[weak self] capture
11Pattern Matching0/20Unlock →
Literals and defaultif caseMatch an OptionalComma (or) patternsRange patternsDestructure a structTuple patternswhile letValue binding with whereEnum associated valuesfor case letMatch guardsOptional ? patternMatch a Resultswitch as an expressionBind the ends, ignore the restMatch an array's shapeguard caseType-casting patternsNested / recursive patterns
12Error Handling0/20Unlock →
try! for invariantstry? with a defaultCompute a fallback from the errorKeep only the successesguard to bail out earlyResult.mapErrorOptional to Resultthrows / do / try / catchHandle errors at the top levelAdd context to an errorCustom error typedefer for cleanupResult.flatMapLocalizedError messageMatch multiple error casesThrowing map stops at the first failureSeveral try calls in a rowFlip an optional ResultrethrowsTranslate one error into another
13Option & Result0/20Unlock →
map an OptionalNil-coalescing fallbackKeep a value only if it passesFlatten a nested OptionalQuick shape check with if casemap with a defaultInspect the errorResult map + defaultResult to OptionalTest the value without unwrappingDrop the nilsflatMap an Optionalguard letFill a nil in placeLazy default on nilOptional chainingReplace, keeping the old valueTake the value outCombine two OptionalsAll present, or nil
14Conversions0/15Unlock →
Value to StringBool as a numberCharacter and Unicode scalarCharacters to StringInt from a StringNumeric conversion via initializersSlice to ArrayString to [Character]Float to Int truncatesBuild a typed collectionData and StringFlexible generic parameterParse with a radixFormat with a radixLosslessStringConvertible
15Collection Conversions0/19Unlock →
Array to SetFlatten nested ArraysDictionary keys to ArrayPairs to a DictionarySet to sorted ArrayUnique and sorted at onceDictionary values to ArrayDictionary to pairsFrequency mapKeys to a SetmapValuesSet operationsIterate keys in orderTwo Arrays to a DictionaryArray and ContiguousArrayGroup into a DictionaryInvert a DictionaryUnique, keeping orderAn Array of a protocol type
16Math0/14Unlock →
17Encoding0/22Unlock →
String to bytesASCII checks and caseBase64 encodeBytes to StringChar to code pointChar digit valueBinary, octal, hex formattingBase64 decodeBig-endian bytesList code pointsEscape a stringHex encodeLittle-endian bytesBytes vs charactersParse a number in a basePercent-decodePercent-encodeLossy UTF-8 decodeCaesar cipherHex decodeROT13XOR cipher
18Random0/20Unlock →
Coin flipRandom Double in [0, 1)Random Int in a rangePick a random elementShuffle a collectionSystem generatorRandom UUIDRandom bytesWeighted true/falseLinear congruential generatorPassword generatorSeeded range drawsReproducible sequencesSample k without replacementSeeded generatorRandom alphanumeric stringRoll many diceFisher-Yates shuffleWeighted choiceNormal distribution
19Data I/O0/18Unlock →
Parse CSV into rowsTab-separated valuesBuild a CSV stringSelect one columnCSV into a number matrixSplit off the headerWhitespace-separated matrixSerialize records to CSVSkip blanks and commentsPrint an aligned tableWrite CSV to a fileWrite a matrix as textDecode JSON to CodableEncode Codable to JSONParse untyped JSONParse key=value configRound-trip write then readDrop unparseable rows
20Linear Algebra0/21Unlock →
Matrix shapeScalar multiplyA matrix of zerosElementwise addArgmax of a vectorDot productFlatten a matrixIdentity matrixOne-hot encodeTraceReLU and sigmoidApply a function elementwiseColumn meansColumn sumsCosine similarityMatrix times vectorTransposeMatrix multiplyMin-max normalize columnsSoftmaxStandardize columns (z-score)
21Text Processing0/16Unlock →
22Date & Time0/12Unlock →
23Memory0/12Unlock →
24Modules0/20Unlock →
import a libraryA namespaceConstants in a namespaceAn enum typeExtend a typeinternal (the default)Namespacing with a structNested typesPrivate membersShorten a nested pathExtension computed propertyfileprivateA struct with methodsA small utility namespaceComputed namespace valuePrivate setter, public getterNested namespacesA protocolProtocol default methodpublic and open
25Macros0/20Unlock →
assert & preconditionA read-only KeyPathmap with a key pathMagic literalsMirror basicsString(describing:) vs reflecting:type(of:)WritableKeyPathMirror display styleMirror child labels@dynamicMemberLookupSwappable behaviorA clamping @propertyWrapperA logging @propertyWrapperA basic @resultBuilder@dynamicCallableDynamic member lookup via KeyPathprojectedValuebuildOptionalbuildEither
26Testing0/20Unlock →
assertTrue with a messageassertNotEqualA basic equality assertionTesting a truth tableMultiple tests with a summaryTesting string outputAsserting on an arrayDoc comments alongside a testTesting an error pathA shared test helperTesting a struct methodTesting an OptionalSkipping a testAsserting a function throwsComparing floats within an epsilonTesting a validation pathTesting a private functionTesting a function that returns ResultTable-driven testsChecking the thrown error's value
27Algorithms0/8Unlock →
28Sorting Algorithms0/12Unlock →
29Expression Parsing0/6Unlock →
30Idioms0/9Unlock →
31OOP & Traits0/8Unlock →
32Trait Objects0/14Unlock →
33Design Patterns0/14Unlock →
35File I/O0/6Unlock →
36Filesystem0/18Unlock →
37Networking0/16Unlock →
38Concurrency0/7Unlock →
39Unsafe & FFI0/14Unlock →
Dereference a raw pointerA C function pointerSize, stride, and alignmentInspect a value's bytesA typed buffer pointerCall a C functionC stringsRaw and mutable raw pointersMutate a value's bytesReinterpret the bitsA mutable buffer pointerPointer arithmeticRaw bytes to typed elementsOwnership through a raw pointer
40Commands0/14Unlock →
41Array0/10Unlock →
43String0/10Unlock →
45Interval0/5Unlock →
46Linked List0/6Unlock →
47Tree0/14Unlock →
Maximum Depth of Binary TreeInvert Binary TreeSame TreeLowest Common Ancestor of a BSTBinary Tree Level Order TraversalSubtree of Another TreeImplement Trie (Prefix Tree)Kth Smallest Element in a BSTValidate Binary Search TreeAdd and Search WordConstruct Binary Tree from Preorder and InorderBinary Tree Maximum Path SumSerialize and Deserialize Binary TreeWord Search II