Swift Quiz: Test Your Swift Knowledge
Pick how many questions you want, choose a difficulty and go. You'll see why each answer is right or wrong, then you can retry to beat your score.
Which company created Swift?
- Apple
- Microsoft
- JetBrains
Do Swift programs need a main function in a playground?
- Yes, always
- No, top-level code runs from top to bottom
- Only for print
- Only on Windows
What does
terminator: ""do in print?- Ends the program
- Removes spaces
- Stops print adding a new line at the end
- Prints nothing
Which quotes does Swift use for strings?
- Single quotes
- Backticks
- Either single or double
- Double quotes
Can Swift run outside Apple devices?
- Yes, Swift is open source and runs on Linux and Windows
- No
- Only in a browser
- Only on Android
What's the difference between let and var?
- let is for numbers, var for text
- var is faster
- There's none
- let values can't change; var values can
What does
Int(9.99)return?- 9
- 10
- 9.99
- nil
Which naming style does Swift use for variables?
- snake_case
- lowerCamelCase
- UPPERCASE
- kebab-case
How do you read the price from
let item = (name: "Pen", price: 1.2)?- item.price
- item["price"]
- item(price)
- item[1].price
Why doesn't Swift convert Int to Double automatically?
- It's a limitation that will be removed
- Doubles aren't supported
- Explicit conversions prevent hidden mistakes and loss of precision
- Ints are always bigger
What is
2 + 3 * 4in Swift?- 14
- 20
- 24
- 9
What does
Int.random(in: 1...6)return?- Always 1
- A Double
- An array of six numbers
- A random whole number from 1 to 6, inclusive
What does
(3.6).rounded()return?- 3
- 4.0
- 3.0
- 4
What does
!trueevaluate to?- false
- true
- nil
- An error
Why does
let x: Double = 7.5 + 2compile when7.5 + count(count an Int variable) doesn't?- It's a bug
- Swift converts literals to strings
- The literal 2 adapts to Double, but a variable already has a fixed type that must be converted
- Variables can't be added
How do you insert a variable's value into a string?
- "${name}"
- "{name}"
- "#name"
- "\(name)"
What does
"abc".uppercased()do to the original string?- Changes it to ABC
- Nothing; it returns a new string
- Deletes it
- Throws an error
What type does
"hello".prefix(2)return?- String
- Character
- [Character]
- Substring
How do you write a string that spans several lines?
- Start and end it with three double quotes
- Use \n only
- Use backticks
- Use single quotes
Is
"Swift" == "swift"true?- Yes
- Only with Foundation
- No, comparison is case-sensitive
- It's an error
What does nil mean in Swift?
- Zero
- No value
- An empty string
- false
What type does
Int("12")return?- Int
- String
- Double
- Int?
What does
if let name { }do (Swift 5.7+)?- Unwraps the optional name into a non-optional constant with the same name
- Declares a new optional
- Sets name to nil
- Compares name with true
What does
a?.b?.cgive if b is nil?- A crash
- An empty value of c's type
- nil
- a
What happens when you force unwrap a nil value?
- The program crashes with "Unexpectedly found nil"
- It returns 0
- It returns an empty string
- It's ignored
Does a Swift switch case fall through to the next case?
- Yes, unless you write break
- Only for strings
- Only with default
- No, never by default
Why does a switch over a String need default?
- A switch must be exhaustive, and there are endless possible strings
- Strings are special
- default is always required
- To add a break
What does
_match in a switch case?- Nothing
- Any value
- Only zero
- Only nil
Are braces optional for a one-line if in Swift?
- No, they're always required
- Yes
- Only with else
- Only in playgrounds
What does
let fee = if isMember { 0.0 } else { 4.99 }require?- Nothing, it works in every version
- A ternary operator
- A switch
- Swift 5.9 or later, where if can be an expression
Does the range
1...3include 3?- Yes
- No
- Only in while loops
- Only with stride
What does
enumerated()give in a for-in loop?- Only positions
- A sorted copy
- Pairs of position and item
- The count
What does
continuedo?- Ends the loop
- Skips to the next pass of the loop
- Restarts from the beginning
- Pauses the app
How do you count 10, 8, 6 ... 0?
- for i in stride(from: 10, through: 0, by: -2)
- for i in 10...0
- for i in 0...10 by 2
- for i in (0..<10).step(2)
What happens with
for i in 5...1?- It counts down
- It does nothing
- It compiles but warns
- The program crashes, because a range's lower bound can't be above its upper bound
Which keyword declares a function in Swift?
- function
- func
- fun
- def
What does
->introduce in a function declaration?- A parameter
- The return type
- A label
- A comment
What is an argument label?
- The function's name
- The parameter's type
- The name callers write before an argument, like from: in move(from: a)
- A comment
When can a function leave out the return keyword?
- Never
- When it returns Void
- When it has no parameters
- When its body is a single expression
Can you assign a new value to a normal parameter inside a function?
- No, parameters are constants; copy them to a var or use inout
- Yes
- Only Ints
- Only with default values
What is the type of
["red", "green"]?- String
- Array
- [Any]
- [String]
What does
[Int]().firstreturn?- 0
- nil
- A crash
- []
What does
xs.firstIndex(of: 7)return if 7 isn't present?- nil
- -1
- 0
- A crash
What does
removeAll { $0 < 0 }do?- Removes the first negative number
- Empties the array
- Removes every item that's less than zero
- Returns a new array
Why does assigning an array to another variable not link them?
- It's a bug
- Arrays are value types: each variable gets its own copy (copied lazily on write)
- Arrays are classes
- Only let arrays are copied
What does reading
dict["key"]return?- An optional value, nil if the key is missing
- The value, always
- The key
- A Bool
What happens when you insert a duplicate into a set?
- An error
- It's added twice
- Nothing; the set keeps one copy
- The set is cleared
What does
Set(["a", "b", "a"]).countreturn?- 3
- 2
- 1
- 0
What does
a.intersection(b)return?- Everything in either set
- Items found in both sets
- Items only in a
- Items only in b
What must dictionary keys and set items be?
- Strings
- Optional
- Sorted
- Hashable
What is a trailing closure?
- A closure at the end of a file
- A closure written after a function call's brackets when it's the last argument
- A closure that returns nothing
- An escaping closure
What does
compactMapdo?- Sorts the array
- Removes duplicates
- Combines items into one value
- Transforms each item and removes the nil results
Do map and filter change the original array?
- Yes
- No, they return new arrays
- Only var arrays
- Only filter does
What does
xs.sorted(by: >)do?- Sorts smallest first
- Reverses the array
- Removes items greater than 0
- Returns a new array sorted largest first
What does it mean that a closure captures a variable?
- It copies the variable once
- It deletes the variable
- It keeps a reference to the variable so it can read and change it later, even after the original scope ends
- It makes the variable constant
What does Swift generate automatically for a struct?
- A class
- A memberwise initializer with a parameter for each property
- A copy method
- A protocol
What is a computed property?
- A property whose value is calculated each time it's read
- A property that stores a calculation once
- A static property
- A let property
When does
didSetrun?- Before the property changes
- Only in the initializer
- After the property changes, with oldValue available
- Never automatically
Can you call a mutating method on a let instance?
- Yes
- No, the instance must be a var
- Only in playgrounds
- Only if it returns a value
Why are structs called value types?
- They only hold numbers
- They have no methods
- They're stored in a database
- Assigning or passing one creates an independent copy
Does a class get a memberwise initializer?
- Yes, like structs
- Only final classes
- Only subclasses
- No, you write init yourself
What does
final classprevent?- Other classes inheriting from it
- Creating instances
- Changing properties
- Using protocols
What does
super.init(...)do in a subclass's initializer?- Creates a second object
- Deletes the parent
- Calls the parent class's initializer to set up the inherited properties
- Copies the object
When does
deinitrun?- When the object is created
- When the last reference to the object goes away and it's destroyed
- Every time a method is called
- Only in structs
Which is the best fit for a class rather than a struct?
- A shared shopping cart that several screens read and update
- A Point with x and y
- A product loaded from JSON
- A colour value
How do you write a case when Swift already knows the enum type?
- .west
- Direction::west
- west()
- "west"
What are associated values?
- Raw values
- Static properties
- Data attached to a specific case, which can differ for each case
- Default values
What's the default raw value of
case smallin an enum with String raw values?- ""
- "small"
- 0
- nil
Which built-in Swift type is an enum?
- String
- Array
- Int
- Optional
What must a method that changes
selfin an enum be marked?- static
- mutating
- override
- final
What does a protocol describe?
- How data is stored
- A class hierarchy
- Requirements (properties and methods) that conforming types must provide
- A file format
What is a protocol extension used for?
- Adding default implementations and shared methods to every conforming type
- Creating new protocols
- Inheriting from classes
- Removing requirements
Which protocol do SwiftUI lists need for their data?
- Codable
- Identifiable
- Comparable
- Equatable
What must you implement to make a type Comparable?
- ==
- description
- hash(into:)
- The < operator
How many protocols can a struct conform to?
- One
- Two
- As many as it needs
- None
Can you extend types you didn't write, such as String?
- No
- Only classes
- Yes
- Only with a subclass
What does a
whereclause do on an extension?- Renames the type
- Limits the extension to cases that meet a condition, such as Element == Int
- Makes it private
- Adds stored properties
Why add each protocol conformance in its own extension?
- It's required
- It's faster at run time
- It hides the protocol
- It keeps related code together and makes the type easier to read
What must a method in an Int extension that changes self be marked?
- mutating
- static
- override
- final
What's a common file naming convention for extensions?
- Extensions.swift for everything
- Type+Feature.swift, such as String+Validation.swift
- ext_string.swift
- StringExtensionsFile.swift
What does
throwsin a function declaration mean?- The function can throw an error that callers must handle
- The function always fails
- The function returns nil
- The function is asynchronous
How do you handle one specific error case and extract its value?
- catch error
- catch MyError.someCase(let value)
- if error == someCase
- try?
What does LocalizedError's errorDescription provide?
- The error's line number
- A stack trace
- A user-friendly message, used by localizedDescription
- An error code
What are the two cases of Result?
- success and failure
- some and none
- ok and error
- true and false
What can a function do instead of catching an error from code it calls?
- Nothing, it must catch
- Use try! always
- Return nil automatically
- Mark itself throws and let the error propagate to its caller
Which of these is a generic type?
- Array
- Int
- String
- Bool
How does Swift usually know what T is in a generic call?
- You always write it
- It's always Any
- It picks Int
- It infers it from the arguments
Which constraint lets a generic type be stored in a Set?
- Comparable
- Hashable
- Codable
- Identifiable
What's a where clause used for on a generic function?
- Loops
- Filtering arrays
- Adding extra requirements, such as C.Element: Equatable
- Error handling
Can a Stack<String> accept an Int?
- Yes
- Only with a cast
- Only at run time
- No, generics keep full type safety
What does ARC stand for?
- Automatic Reference Counting
- Automatic Resource Control
- Array Reference Collection
- Apple Runtime Cache
When does deinit run?
- When the instance is created
- Just before the instance is freed, when its strong reference count reaches zero
- When the app closes
- Whenever a property changes
What's the difference between weak and unowned?
- There's none
- unowned keeps objects alive
- weak only works with structs
- weak is optional and becomes nil; unowned isn't optional and crashes if used after the object is freed
Why must a delegate protocol be marked AnyObject to use weak?
- For speed
- Only class instances can be referenced weakly, and AnyObject limits the protocol to classes
- It's needed for Codable
- It makes the protocol public
What is a strong reference cycle?
- Objects that strongly reference each other so neither count reaches zero and neither is freed
- A loop that never ends
- A recursive function
- A closure called twice
How do you call an async throwing function?
- await try
- async try
- try await
- try async
How do you start async work from a normal button action?
- Call it directly
- Wrap it in Task { }
- Use DispatchQueue only
- Mark the button async
What does @MainActor ensure?
- Code runs in parallel
- Code runs on the main thread, which UI updates require
- Code never throws
- Code is cached
What's the best tool for downloading a list of images whose length is only known at run time?
- One async let per image
- A for loop with await, one at a time
- An actor
- A task group
How does cancellation work in Swift concurrency?
- It's cooperative: code must check Task.isCancelled or call Task.checkCancellation()
- Tasks stop instantly
- It's impossible
- It only works for actors
What does JSONEncoder produce?
- A String
- Data
- A Dictionary
- A URL
Why is decode called with try?
- It throws an error if the JSON doesn't match the type
- It's async
- It returns an optional
- It's required for all functions
How do you decode a JSON array of products?
- decode(Product.self, ...)
- decodeArray(Product.self, ...)
- decode([Product].self, ...)
- decode(Array.self, ...)
Which strategy parses dates like 2026-03-01T10:00:00Z?
- .secondsSince1970
- .iso8601
- .deferredToDate
- .millisecondsSince1970
What does .sortedKeys in outputFormatting do?
- Sorts array items
- Removes duplicate keys
- Compresses the JSON
- Writes object keys in alphabetical order, giving stable output
What kind of Swift type is usually used for a SwiftUI view?
- class
- struct
- enum
- actor
What does Image(systemName: "star.fill") show?
- An image from your assets folder
- A photo from the library
- An emoji
- An SF Symbols icon
Why does the order of modifiers matter?
- Each modifier wraps the view produced by the previous one
- It doesn't
- Only the first modifier is applied
- Modifiers are sorted alphabetically
What does #Preview do?
- Runs the app on a device
- Takes a screenshot
- Shows the view live in Xcode's canvas
- Publishes the app
How should text sizes usually be set in SwiftUI?
- With fixed point sizes
- In pixels
- With semantic fonts like .headline and .body, which scale with the user's settings
- They can't be changed
What does the $ prefix in $name create?
- A copy
- A string
- An optional
- A binding, a two-way connection to the value
What happens when a @State value changes?
- Nothing until the app restarts
- SwiftUI recomputes the view's body and updates the screen
- The view is deleted
- It must be saved manually
What does the @Observable macro do to a class?
- Makes it a struct
- Saves it to disk
- Lets SwiftUI track which properties each view reads and update those views when they change
- Makes it thread-safe
How does a view read a model placed with .environment(store)?
- @State var store
- @Environment(Store.self) private var store
- @Binding var store
- It can't
When should a child view use a plain let property instead of @Binding?
- Never
- When the value is a class
- When the value is optional
- When it only needs to read the value, not change it
What does onDelete add to a ForEach inside a List?
- Swipe to delete on each row
- A delete button in the toolbar
- An alert
- Nothing visible
How do you close a sheet from inside it?
- dismissSheet()
- Read @Environment(\.dismiss) and call dismiss()
- Set the view to nil
- Use a NavigationLink
How do you show a list of plain Strings?
- Strings can't be shown in lists
- Pass id: \.self, because Strings aren't Identifiable
- Wrap each in a UUID
- Convert them to Ints
What does .searchable(text: $query) do?
- Searches the web
- Sorts the list
- Adds a search field bound to query, which you use to filter the data
- Highlights rows
What is TabView for?
- Organising an app's top-level sections, switched with a tab bar
- Showing tables of data
- Indenting text
- Pushing detail screens
What does @testable import do?
- Runs the tests
- Gives the test target access to the app module's internal code
- Imports XCTest
- Marks code as finished
How do you check that code throws a specific error?
- #expect(error)
- #expect(throws: MyError.someCase) { try ... }
- try! inside the test
- XCTFail()
Can Swift Testing tests be async?
- No
- Only with XCTest
- Yes, mark them async (and throws) and use await
- Only on the main thread
What groups related tests in Swift Testing?
- A type marked @Suite
- A class that inherits from XCTestCase
- A protocol
- A folder named Tests
Which XCTest function compares two values?
- #expect
- assertSame
- XCTCompare
- XCTAssertEqual
What is the usual default access level for Swift declarations?
- internal
- public
- open
What does private(set) change on an otherwise internal property?
- It makes every method public.
- It restricts writes while leaving the getter's normal visibility available.
- It encrypts the stored value.
What does init? communicate to its caller?
- Every stored property becomes optional.
- The instance is always created and may be repaired later.
- Construction can return nil instead of a valid instance.
Where does a class convenience initializer delegate?
- To another initializer in the same class, eventually reaching designated initialization.
- Directly to any unrelated class instance.
- Only to a setter called after initialization.
What normally happens on a lazy property's second sequential read?
- The initializer must execute again.
- The stored first-access result is read.
- The enclosing object is recreated.
Which member is required for a basic property wrapper's wrapped access?
- mainClass
- hashBucket
- wrappedValue
What does KeyPath<Product, String> permit?
- Reading a String result through a supported Product property route.
- Accessing arbitrary fields chosen by unchecked strings.
- Assigning any property of every type.
Why does the score table return Int? from its subscript?
- Bracket syntax requires all Swift results to be optional.
- A requested name might not exist.
- Every stored score is necessarily invalid.
What does as? return when a runtime cast is incompatible?
- A rounded numeric value.
- A silently constructed object of the requested type.
- nil.
Which operation parses decimal text into an integer?
- Int(text).
- text as? Int.
- text is Int.
Who selects the underlying type of an opaque function result?
- Each caller replaces it with any unrelated conforming type.
- The producing function's implementation selects one stable underlying type.
- A runtime string chooses it without constraints.
Which interface naturally supports Product and Customer together when both are Named?
- A claim that the two concrete types are identical.
- A forced cast of every Customer into Product.
- [any Named].
What is not universally promised by Sequence alone?
- Repeated identical traversal and indexed random access.
- An element type.
- Producing elements through an iterator.
Why is slice[0] unsafe for an arbitrary ArraySlice?
- Slices always convert integers into strings.
- Its indices may start at an original nonzero position.
- Every slice is empty.
What does String.count measure in this guide's text model?
- Always exactly the number of Unicode scalars.
- UTF-8 bytes.
- Characters, represented as extended grapheme clusters.
Why can NSRange require conversion before Swift string slicing?
- Foundation ranges can use UTF-16 offsets rather than Character-based String.Index positions.
- NSRange automatically encrypts text.
- Swift strings never contain emoji.
Which operation requires the complete input to fit the stock pattern?
- firstMatch
- wholeMatch
- A search for any substring
Why does the parser check 1...100 after matching digits?
- Matching digits proves every quantity is available in stock.
- Regex automatically authorizes the caller.
- Text shape and business range are different validation rules.
What normally groups source files into an importable module?
- A declared target.
- The executable's printed output.
- Any arbitrary folder name with no manifest relationship.
Why can StockCLI call stockTotal?
- The product's lowercase name disables access control.
- It depends on StockCore and the function is public across modules.
- Every package file automatically shares private access.
What does Foundation Date represent?
- Only a formatted string.
- One permanent local calendar date with a stored display zone.
- An absolute moment independent of calendar and time-zone presentation.
Which API expresses calendar-based addition of seven days?
- Calendar.date(byAdding: .day, value: 7, to: ...).
- A guessed fixed month length in seconds.
- Lexical sorting of localized display text.
What does an atomic whole-file write primarily help avoid?
- Every possible concurrent writer conflict across all processes.
- Exposing the destination as a partially written new document during replacement.
- All JSON schema evolution errors.
Why keep missing and corrupt files distinguishable?
- Corrupt files always prove that no user data existed.
- Decoding errors cannot ever occur.
- First-launch defaults and recovery of damaged data can need different policies.
What should happen before decoding an HTTP body as a success model?
- Check that the response and status match the endpoint's accepted contract.
- Log every authorization header.
- Assume readable bytes always mean success.
Why can retrying a submitted payment be unsafe?
- Decoding a response prevents duplicate requests.
- The server may have performed the effect even if its response was lost.
- All HTTP requests are automatically reversible.
What does for await add to sequence iteration?
- Automatic deep copying of every shared object.
- A promise that every value is already stored in an array.
- The next element can require asynchronous waiting.
What does finish do for the finite example?
- Signals normal completion so iteration can end after retained values are consumed.
- Permanently stores all values in a database.
- Starts a second consumer thread.
Which transfer design is straightforward for these examples?
- An unprotected mutable reference shared everywhere.
- An immutable Sendable snapshot with Sendable fields.
- unchecked Sendable added without any safety design.
What does unchecked Sendable do?
- Automatically creates a mutex around every field.
- Prevents all stale network responses.
- Relies on the author's safety promise rather than installing synchronization.
What can happen while an actor method is suspended at await?
- Other actor work can run and change isolated state.
- Every external effect is rolled back.
- All actor state is permanently frozen.
What should a latest-result guard combine in one actor operation?
- Cancelling every unrelated task globally.
- Checking the ticket and updating the current result.
- Only printing the ticket.
Why keep a quantity draft as String while editing?
- Numeric ranges never need checking.
- Strings automatically authorize stock updates.
- Temporary empty or partial input is legitimate before a valid Int request exists.
What should accompany color-based error styling?
- A useful textual explanation associated with the relevant field.
- Only a smaller placeholder with no label.
- A hidden error that appears only in debug logs.
Which object establishes schema and storage configuration?
- A temporary TextField binding.
- ModelContainer.
- A formatted JSON string alone.
Why sort the main example's fetch?
- Every database returns insertion order permanently.
- Sorting encrypts the models.
- To make the result order an explicit contract for expected output.
About the Swift quiz
This Swift quiz covers every lesson in the course, from print and constants to concurrency, SwiftUI and testing. Many questions show a few lines of Swift and ask what they print, because predicting output is the best way to check that you understand how the language behaves. Others check vocabulary you'll meet in Apple's documentation and Xcode's error messages, such as "optional", "closure", "protocol", "binding" and "actor".
If you're still in the beginner stage, choose Easy and a topic you've just finished, such as strings or optionals. After the intermediate lessons, try Mixed with 10 questions to practise collections, structs and protocols together. Save Exam mode for the end of the course: it hides the answers until you finish, so it's an honest check of what you remember.
When you miss a question, read the explanation and revisit the lesson linked in your results. Swift mistakes often come from small details: whether a range uses ... or ..<, whether a type is a struct or a class, or what try? returns on failure. Spotting them in a quiz makes them easy to avoid in real code.
The question bank holds 161 questions drawn from 43 Swift lessons: 43 easy, 93 medium and 25 hard. Every time you start, the quiz picks a fresh random selection that matches your settings, so retaking it is a good way to practise. After each answer, or at the end in exam mode, you'll see why the right answer is right, and every question you miss links back to the lesson that teaches it.
What the Swift quiz covers
Beginner
Intermediate
Advanced
Language reference
- 26Swift Access Control and Module Boundaries
- 27Swift Initialization Beyond the Basics
- 28Swift Lazy Properties and Property Wrappers
- 29Swift Subscripts and Key Paths
- 30Swift Type Casting, Any and AnyObject
- 31Swift Opaque and Existential Protocol Types
- 32Swift Sequence, Collection and Lazy Algorithms
- 33Swift Unicode Strings and String.Index
- 34Swift Native Regex and Text Parsing