Update dataset_3.jsonl
Browse files4 unmodified lines56789104 unmodified lines{"question": "What is a session in PHP?", "answer": "A session allows you to store user data across multiple pages. Start a session with `session_start()`. Store data in `$_SESSION`. Example:\n$_SESSION['user_id'] = 123;\necho $_SESSION['user_id'];\nSessions use a cookie (PHPSESSID) to identify the user."}{"question": "How do you destroy a session?", "answer": "Use `session_destroy()` to delete all session data on the server. To completely log out a user, also unset the session cookie and clear the `$_SESSION` array. Example:\nsession_start();\n$_SESSION = [];\nsession_destroy();"}{"question": "What is a cookie in PHP?", "answer": "A cookie is a small piece of data stored on the client's browser. Set it with `setcookie()`. Example:\nsetcookie('theme', 'dark', time() + 86400, '/');\nRead it with `$_COOKIE['theme']`. Cookies are sent with every request, so keep them small."}{"question": "What is the difference between `include` and `require`?", "answer": "`include` produces a warning if the file is missing but continues execution. `require` produces a fatal error and stops execution. `include_once` and `require_once` ensure the file is included only once, preventing redeclaration errors."}{"question": "How do you handle errors in PHP?", "answer": "Use `try-catch` blocks for exceptions. Configure error reporting with `error_reporting()` and `ini_set('display_errors', 0)` in production. Log errors to a file using `error_log()`. Custom error handlers can be set with `set_error_handler()`."}{"question": "What is an exception in PHP?", "answer": "An exception is an object representing an error condition. Throw one with `throw new Exception('Message')`. Catch it with `catch (Exception $e)`. Exceptions allow graceful error handling and separation of error logic from business logic."}4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261274 unmodified lines{"question": "What is a session in PHP?", "answer": "A session allows you to store user data across multiple pages. Start a session with `session_start()`. Store data in `$_SESSION`. Example:\n$_SESSION['user_id'] = 123;\necho $_SESSION['user_id'];\nSessions use a cookie (PHPSESSID) to identify the user."}{"question": "How do you destroy a session?", "answer": "Use `session_destroy()` to delete all session data on the server. To completely log out a user, also unset the session cookie and clear the `$_SESSION` array. Example:\nsession_start();\n$_SESSION = [];\nsession_destroy();"}{"question": "What is a cookie in PHP?", "answer": "A cookie is a small piece of data stored on the client's browser. Set it with `setcookie()`. Example:\nsetcookie('theme', 'dark', time() + 86400, '/');\nRead it with `$_COOKIE['theme']`. Cookies are sent with every request, so keep them small."}{"question": "What is the difference between let and var in Swift?", "answer": "let declares a constant whose value cannot be changed after initialization, while var declares a variable that can be reassigned:\nlet highTemp = 70\n// highTemp = 60 // Error: cannot assign to a constant\n\nvar lowTemp = 50\nlowTemp = 40 // OK\nlowTemp += 5 // OK\nUse let by default for values that do not change, and var only when mutation is needed. The compiler will suggest let when it detects a variable is never reassigned [citation:2]."}{"question": "What is an Optional in Swift?", "answer": "An Optional represents a value that may be present or absent (nil). It is an enum with two cases: .some(Wrapped) and .none:\nlet number: Int? = Optional.some(42)\nlet noNumber: Int? = Optional.none\nprint(noNumber == nil) // true\nThe shorthand Int? is preferred over Optional<Int>. You must unwrap an Optional before using its value, and Swift provides several safe unwrapping techniques [citation:3][citation:13]."}{"question": "How do you safely unwrap an Optional in Swift?", "answer": "Common safe unwrapping techniques include optional binding and optional chaining:\n// if let\nif let path = imagePaths[\"star\"] {\n print(\"Found: \\(path)\")\n}\n\n// guard let\nguard let path = imagePaths[\"star\"] else { return }\nprint(path)\n\n// Optional chaining\nif imagePaths[\"star\"]?.hasSuffix(\".png\") == true { }\n\n// Nil-coalescing\nlet p = imagePaths[\"heart\"] ?? \"/default.png\"\nAvoid forced unwrapping with ! unless you are certain the value is non-nil [citation:3][citation:13]."}{"question": "What is optional chaining in Swift?", "answer": "Optional chaining uses ?. to access properties, methods, and subscripts on an Optional without force unwrapping. If the Optional is nil, the entire expression returns nil:\nlet count = person?.name?.count\n// If person or name is nil, count is nil\nlet isPNG = imagePaths[\"star\"]?.hasSuffix(\".png\")\n// isPNG is Bool?\nThis avoids runtime crashes and lets you chain multiple accesses safely [citation:3][citation:13]."}{"question": "What is the nil-coalescing operator in Swift?", "answer": "The ?? operator returns the left operand if it is non-nil, otherwise the right default value:\nlet heartPath = imagePaths[\"heart\"] ?? \"/images/default.png\"\nprint(heartPath) // prints the default if \"heart\" is missing\nYou can chain multiple ?? operators:\nlet path = a ?? b ?? c ?? \"/default\"\nThe right side is evaluated lazily (autoclosure) [citation:3][citation:13]."}{"question": "What is a protocol in Swift?", "answer": "A protocol defines a blueprint of methods, properties, and requirements that conforming types must implement. It is similar to an interface in other languages:\nprotocol FullyNamed {\n var full: String { get }\n}\n\nstruct Person: FullyNamed {\n var full: String\n}\nProtocols can be adopted by classes, structs, and enums. A type can conform to multiple protocols, listed after a colon and separated by commas [citation:4]."}{"question": "What are property requirements in a protocol?", "answer": "A protocol can require properties with { get } or { get set }:\nprotocol Named {\n var name: String { get }\n var age: Int { get set }\n}\n{ get } means the property must be gettable (read-only or read-write). { get set } means it must be both gettable and settable. A constant stored property or read-only computed property cannot satisfy { get set }. Type properties use static in the protocol declaration [citation:4]."}{"question": "What is the difference between class and struct in Swift?", "answer": "Classes are reference types: instances are shared through references, and changing a property mutates the shared object. Structs are value types: instances are copied on assignment, and changing a property of a let struct is a compile error:\n// Class: let reference can still mutate properties\nlet person = Person(name: \"Einstein\")\nperson.age = 85 // OK\n\n// Struct: let value cannot mutate\nlet p = Personnage(name: \"Einstein\", age: 80)\n// p.age = 85 // Error\nUse structs by default for value semantics, and classes when identity or inheritance is needed [citation:12]."}{"question": "What is ARC in Swift?", "answer": "Automatic Reference Counting (ARC) manages memory for class instances. The compiler inserts retain and release operations: retain increments the reference count, release decrements it, and when the count reaches zero, the object is deallocated:\nclass Traveler { var name: String }\nlet a = Traveler(name: \"Lily\") // count = 1\nlet b = a // count = 2\n// after last use, count returns to 0 and object is freed\nARC works only for reference types. Structs and enums are value types and do not need ARC [citation:5][citation:15]."}{"question": "What is a strong reference cycle and how do you break it?", "answer": "A strong reference cycle occurs when two objects hold strong references to each other, so neither can be deallocated:\nclass Traveler { var account: Account? }\nclass Account { var traveler: Traveler? }\nlet t = Traveler()\nlet a = Account()\nt.account = a\na.traveler = t\n// both reference counts stay > 0 forever\nBreak the cycle with a weak or unowned reference on one side:\nclass Account { weak var traveler: Traveler? }\nWeak references become nil when the object is deallocated, while unowned references assume the object outlives the reference [citation:15]."}{"question": "What is the difference between weak and unowned references?", "answer": "Both do not participate in reference counting and break cycles. A weak reference is always Optional and becomes nil when the referenced object is deallocated. An unowned reference is non-Optional and assumes the object lives at least as long as the reference; accessing it after deallocation crashes. Use weak when the referenced object may become nil, and unowned when the relationship guarantees the object outlives the reference [citation:15]."}{"question": "How do you write a Hello World app in SwiftUI?", "answer": "A minimal SwiftUI app uses a struct conforming to View:\nimport SwiftUI\n\nstruct ContentView: View {\n var body: some View {\n Text(\"Hello, World!\")\n .padding()\n }\n}\n\n@main\nstruct MyApp: App {\n var body: some Scene {\n WindowGroup {\n ContentView()\n }\n }\n}\nThe @main attribute marks the app entry point, and WindowGroup hosts the root view [citation:1]."}{"question": "How do you display a list of data in SwiftUI?", "answer": "Use List with ForEach over an Identifiable collection:\nstruct Person: Identifiable {\n let id = UUID()\n var name: String\n}\n\nstruct StaffList: View {\n var staff: [Person]\n var body: some View {\n List {\n ForEach(staff) { person in\n Text(person.name)\n }\n }\n }\n}\nIdentifiable requires an id property. For sections, wrap ForEach in Section with a header [citation:9]."}{"question": "How do you create sections in a SwiftUI List?", "answer": "Wrap each group in a Section with a header:\nList {\n ForEach(company.departments) { department in\n Section {\n ForEach(department.staff) { person in\n PersonRowView(person: person)\n }\n } header: {\n Text(department.name)\n }\n }\n}\nSections group related rows and improve navigation in hierarchical data [citation:9]."}{"question": "How do you make an HTTP request in Swift?", "answer": "Use URLSession with URLRequest for custom methods such as POST:\nvar request = URLRequest(url: URL(string: \"https://api.example.com/post\")!)\nrequest.httpMethod = \"POST\"\nrequest.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\nrequest.httpBody = jsonData\n\nlet task = URLSession.shared.dataTask(with: request) { data, response, error in\n guard let data = data, error == nil else { return }\n let result = String(decoding: data, as: UTF8.self)\n print(result)\n}\ntask.resume()\nA common mistake is passing the URL instead of the request to dataTask, which performs a GET instead of the configured method [citation:7]."}{"question": "What is the difference between dataTask(with: URL) and dataTask(with: URLRequest)?", "answer": "dataTask(with: URL) always performs a GET request with default settings. dataTask(with: URLRequest) uses the configured request, including HTTP method, headers, and body:\n// GET only\nURLSession.shared.dataTask(with: url)\n\n// Uses configured POST, headers, body\nURLSession.shared.dataTask(with: request)\nIf you build a URLRequest but pass the URL to dataTask, your method and body are ignored [citation:7]."}{"question": "What is SwiftData?", "answer": "SwiftData is Apple's persistence framework that integrates with SwiftUI. You define models with the @Model macro, and SwiftData manages storage in a ModelContext:\nimport SwiftData\n\n@Model\nclass Trip {\n var name: String\n var destination: String\n}\nViews use @Query to fetch data, and the modelContainer modifier sets up the schema. SwiftData replaces in-memory data sources with persistent storage automatically [citation:8]."}{"question": "How do you define a SwiftData model?", "answer": "Use the @Model macro on a class. Replace @Observable with @Model, and ensure stored properties are compatible with persistence:\nimport SwiftData\n\n@Model\nclass Activity {\n var name: String\n var date: Date\n var isCompleted: Bool\n\n init(name: String, date: Date = .now, isCompleted: Bool = false) {\n self.name = name\n self.date = date\n self.isCompleted = isCompleted\n }\n}\nSwiftData generates observable conformance and persistence support automatically [citation:8]."}{"question": "How do you set up a SwiftData model container in SwiftUI?", "answer": "Attach the modelContainer modifier to the root view:\n@main\nstruct MyApp: App {\n var body: some Scene {\n WindowGroup {\n ContentView()\n }\n .modelContainer(for: [Trip.self, Activity.self])\n }\n}\nThis creates the schema and persistent store. Views can then use @Query and @Environment(\\.modelContext) to fetch and modify data [citation:8]."}{"question": "How do you fetch data with @Query in SwiftData?", "answer": "Declare a @Query property in a view:\nstruct TripListView: View {\n @Query var trips: [Trip]\n\n var body: some View {\n List(trips) { trip in\n Text(trip.name)\n }\n }\n}\n@Query automatically fetches and observes changes. You can add a sort or predicate:\n@Query(sort: \\Trip.name) var trips: [Trip] [citation:8]"}{"question": "How do you insert data with SwiftData?", "answer": "Use the modelContext from the environment:\n@Environment(\\.modelContext) private var context\n\nfunc addTrip() {\n let trip = Trip(name: \"Summer\", destination: \"Paris\")\n context.insert(trip)\n}\nSwiftData auto-saves by default. You can call try context.save() explicitly if needed [citation:8]."}{"question": "What is async/await in Swift?", "answer": "async marks a function that can suspend, and await marks a suspension point:\nfunc loadPhoto() async -> UIImage? {\n let data = await fetchData()\n return UIImage(data: data)\n}\nWhile suspended, the thread is free to do other work. The main actor keeps UI responsive, and background work runs off the main thread [citation:6]."}{"question": "What is @MainActor in Swift?", "answer": "@MainActor isolates code to the main thread, which is required for UI updates:\n@MainActor\nclass ViewModel: ObservableObject {\n @Published var items: [Item] = []\n\n func load() async {\n items = await fetchItems()\n }\n}\nIn Xcode 26, new projects enable main actor by default, so types are implicitly @MainActor unless marked nonisolated [citation:6]."}{"question": "What is the nonisolated keyword in Swift concurrency?", "answer": "nonisolated removes a type or method from the main actor isolation, allowing it to run on background threads:\nnonisolated class PhotoProcessor {\n func process(_ image: UIImage) async -> UIImage {\n // runs off the main actor\n }\n}\nUse it for expensive computation that should not block the UI [citation:6]."}{"question": "What is the @concurrent attribute in Swift?", "answer": "@concurrent tells Swift to always switch to a background thread when running a method:\n@concurrent\nfunc process(_ image: UIImage) async -> UIImage {\n // always off the main thread\n}\nCombine it with nonisolated on the type to decouple from @MainActor [citation:6]."}{"question": "How do you run two async tasks in parallel in Swift?", "answer": "Use async let for concurrent tasks:\nasync let a = fetchA()\nasync let b = fetchB()\nlet (resultA, resultB) = await (a, b)\nBoth tasks start immediately and run in parallel. The concurrent thread pool schedules them on different threads if possible [citation:6]."}{"question": "What is XCTest and how do you write a test case?", "answer": "XCTest is Apple's testing framework. Create a subclass of XCTestCase and add methods starting with test:\nimport XCTest\n\nclass TableValidationTests: XCTestCase {\n func testEmptyTableRowAndColumnCount() {\n let table = Table()\n XCTAssertEqual(table.rowCount, 0, \"Row count was not zero.\")\n XCTAssertEqual(table.columnCount, 0, \"Column count was not zero.\")\n }\n}\nXcode automatically detects test methods in test targets [citation:10]."}{"question": "What are common XCTAssert functions in Swift?", "answer": "Common assertions include:\nXCTAssertTrue(condition)\nXCTAssertFalse(condition)\nXCTAssertEqual(a, b)\nXCTAssertNotEqual(a, b)\nXCTAssertNil(value)\nXCTAssertNotNil(value)\nXCTAssertThrowsError(try expression)\nEach takes an optional message parameter for failure diagnostics [citation:10]."}{"question": "How do you create a new iOS project in Xcode?", "answer": "Open Xcode, click Create a new Xcode project, choose iOS and App (or Single View Application), then fill in product name, team, organization identifier, and select Swift as the language. Save the project, and Xcode generates the project structure with a default ContentView and App entry point [citation:1]."}{"question": "What is the difference between if let and guard let?", "answer": "if let scopes the unwrapped value to the if block:\nif let name = optionalName {\n print(name)\n} // name is out of scope here\nguard let exits the current scope if the value is nil, leaving the unwrapped value available afterward:\nguard let name = optionalName else { return }\nprint(name) // available here\nguard is preferred for early exits and validating preconditions [citation:3]."}{"question": "What is a computed property in Swift?", "answer": "A computed property calculates its value on access instead of storing it:\nvar fullName: String {\n return \"\\(firstName) \\(lastName)\"\n}\nIt can be read-only or have a setter:\nvar area: Double {\n get { width * height }\n set { width = sqrt(newValue) }\n}\nComputed properties are common in protocols and view models [citation:4]."}{"question": "What is a closure in Swift?", "answer": "A closure is a self-contained block of functionality that can be passed around:\nlet greet = { (name: String) -> String in\n return \"Hello, \\(name)\"\n}\nprint(greet(\"Alice\"))\nClosures capture variables from their surrounding context. They are used extensively in SwiftUI and asynchronous code [citation:6]."}{"question": "What is trailing closure syntax in Swift?", "answer": "If a closure is the last argument, you can write it outside the parentheses:\nUIView.animate(withDuration: 0.3) {\n view.alpha = 0\n}\nThis is common with SwiftUI and completion handlers. Multiple trailing closures use labeled syntax:\nfoo { } completion: { } [citation:9]"}{"question": "What is the @State property wrapper in SwiftUI?", "answer": "@State declares view-local mutable state. SwiftUI manages storage and re-renders when it changes:\nstruct CounterView: View {\n @State private var count = 0\n\n var body: some View {\n Button(\"Count: \\(count)\") {\n count += 1\n }\n }\n}\nUse @State for simple value types owned by the view. For shared state, use @StateObject or @ObservedObject [citation:9]."}{"question": "What is the difference between @StateObject and @ObservedObject?", "answer": "@StateObject creates and owns an ObservableObject, keeping it alive across view updates. @ObservedObject receives an object from outside and does not own it:\n@StateObject var model = MyModel() // owned\n@ObservedObject var model: MyModel // injected\nUse @StateObject when the view is responsible for the object's lifetime, and @ObservedObject for dependencies passed in [citation:6]."}{"question": "What is @Environment in SwiftUI?", "answer": "@Environment reads values from the environment, such as the model context or color scheme:\n@Environment(\\.modelContext) private var context\n@Environment(\\.colorScheme) private var scheme\nValues are injected by modifiers such as modelContainer or environment. It is a clean way to pass dependencies without explicit parameters [citation:8]."}{"question": "What is the Identifiable protocol?", "answer": "Identifiable requires a stable id property so collections can be rendered efficiently in List and ForEach:\nstruct Person: Identifiable {\n let id = UUID()\n var name: String\n}\nForEach uses id to track insertions, deletions, and updates. Without Identifiable, you can use ForEach(array, id: \\.self) for hashable values [citation:9]."}{"question": "What is a mutating method in Swift?", "answer": "A mutating method modifies the instance it belongs to. Structs and enums require the mutating keyword for methods that change properties:\nstruct Counter {\n var value = 0\n mutating func increment() {\n value += 1\n }\n}\nProtocols that require mutating methods declare them with mutating in the protocol definition [citation:4]."}{"question": "What is a static property or method in Swift?", "answer": "static members belong to the type rather than an instance:\nstruct Math {\n static let pi = 3.14159\n static func square(_ x: Double) -> Double { x * x }\n}\nprint(Math.pi)\nprint(Math.square(4))\nIn protocols, type property requirements are prefixed with static [citation:4]."}{"question": "What is an extension in Swift?", "answer": "An extension adds functionality to an existing type without subclassing:\nextension String {\n var isPalindrome: Bool {\n self == String(self.reversed())\n }\n}\nprint(\"level\".isPalindrome) // true\nExtensions can add computed properties, methods, initializers, and protocol conformance. They cannot add stored properties [citation:4]."}{"question": "How do you add protocol conformance with an extension?", "answer": "Declare conformance in an extension to keep the type definition clean:\nstruct Person {\n var name: String\n}\n\nextension Person: CustomStringConvertible {\n var description: String { name }\n}\nThis is useful for organizing code and conforming to protocols without modifying the original declaration [citation:4]."}{"question": "What is a failable initializer in Swift?", "answer": "A failable initializer returns nil when initialization fails:\nstruct Temperature {\n let celsius: Double\n init?(celsius: Double) {\n guard celsius >= -273.15 else { return nil }\n self.celsius = celsius\n }\n}\nlet t = Temperature(celsius: -300) // nil\nCallers must handle the Optional result [citation:3]."}{"question": "What is the difference between a failable initializer and a throwing initializer?", "answer": "A failable initializer returns nil on failure (init?). A throwing initializer throws an error with detailed information (init throws):\ninit?(rawValue: String) // returns nil\ninit(contentsOf url: URL) throws // throws an error\nUse failable for simple absence and throwing for recoverable errors with context [citation:3]."}{"question": "What is the #available check in Swift?", "answer": "#available checks if an API is available on the current OS version:\nif #available(iOS 17, *) {\n // use iOS 17 API\n} else {\n // fallback\n}\nThe asterisk is required and covers other platforms. This enables backward-compatible code when adopting new APIs [citation:6]."}{"question": "What is the @available attribute in Swift?", "answer": "@available marks the availability of a declaration:\n@available(iOS 15, *)\nfunc newFeature() { }\nCalling an unavailable API produces a compile error. It is used for API evolution and deprecation:\n@available(*, deprecated, message: \"Use newMethod\")\nfunc oldMethod() { } [citation:6]"}{"question": "What is a Result type in Swift?", "answer": "Result<Success, Failure> represents either a success value or an error:\nfunc fetch(completion: (Result<Data, Error>) -> Void) {\n // completion(.success(data)) or completion(.failure(error))\n}\nswitch result {\ncase .success(let data): print(data)\ncase .failure(let error): print(error)\n}\nIt is useful for callback-based APIs before adopting async/await [citation:7]."}{"question": "How do you decode JSON in Swift?", "answer": "Use JSONDecoder with Codable types:\nstruct User: Codable {\n let name: String\n let age: Int\n}\n\nlet data = jsonString.data(using: .utf8)!\nlet user = try JSONDecoder().decode(User.self, from: data)\nCodingKeys customize field names, and dateDecodingStrategy handles dates. Conform to Codable (Encodable & Decodable) for automatic synthesis [citation:7]."}{"question": "How do you encode JSON in Swift?", "answer": "Use JSONEncoder:\nlet user = User(name: \"Alice\", age: 30)\nlet data = try JSONEncoder().encode(user)\nlet jsonString = String(data: data, encoding: .utf8)\nFor the request body, set Content-Type to application/json and assign the data to httpBody [citation:7]."}{"question": "What is a typealias in Swift?", "answer": "typealias creates a new name for an existing type:\ntypealias CompletionHandler = (Result<Data, Error>) -> Void\ntypealias UserID = UUID\nIt improves readability without creating a new type. Generic typealiases can add constraints [citation:4]."}{"question": "What is an associated type in a protocol?", "answer": "An associated type is a placeholder type used in a protocol:\nprotocol Container {\n associatedtype Item\n mutating func append(_ item: Item)\n var count: Int { get }\n}\nstruct IntStack: Container {\n typealias Item = Int\n // ...\n}\nAssociated types make protocols generic-like. Swift infers them from implementations [citation:4]."}{"question": "What is opaque return type (some View) in SwiftUI?", "answer": "some View means the function returns a specific but unnamed type conforming to View:\nvar body: some View {\n Text(\"Hello\")\n}\nThe compiler knows the concrete type but callers only see the protocol. This enables efficient view composition without exposing implementation details [citation:9]."}{"question": "What is @ViewBuilder in SwiftUI?", "answer": "@ViewBuilder is a result builder that composes multiple views into a single view:\n@ViewBuilder\nfunc content() -> some View {\n Text(\"A\")\n Text(\"B\")\n}\nIt enables the trailing closure syntax used in VStack, HStack, List, and other containers [citation:9]."}{"question": "What is the difference between VStack, HStack, and ZStack?", "answer": "VStack arranges views vertically, HStack horizontally, and ZStack overlays them back-to-front:\nVStack {\n Text(\"Top\")\n Text(\"Bottom\")\n}\nHStack {\n Text(\"Left\")\n Text(\"Right\")\n}\nZStack {\n Image(\"background\")\n Text(\"Overlay\")\n}\nStacks accept alignment and spacing parameters [citation:9]."}{"question": "What is the @Published property wrapper?", "answer": "@Published is used in ObservableObject to notify SwiftUI of changes:\nclass ViewModel: ObservableObject {\n @Published var items: [Item] = []\n}\nWhen items changes, subscribed views re-render. Combine @Published with @StateObject or @ObservedObject in views [citation:6]."}{"question": "What is the Combine framework?", "answer": "Combine is Apple's reactive programming framework for handling asynchronous events. Publishers emit values over time, and subscribers receive them:\nlet cancellable = URLSession.shared.dataTaskPublisher(for: url)\n .map(\\.data)\n .decode(type: User.self, decoder: JSONDecoder())\n .sink(receiveCompletion: { _ in }, receiveValue: { user in\n print(user)\n })\nSwift concurrency (async/await) is increasingly replacing Combine for new code [citation:6]."}{"question": "What is a Task in Swift concurrency?", "answer": "Task starts an asynchronous operation that runs concurrently:\nTask {\n let data = await fetchData()\n await MainActor.run {\n self.items = data\n }\n}\nTasks inherit the actor context where created. Use Task.detached for a completely independent task. Tasks support cancellation [citation:6]."}{"question": "How do you cancel a Task in Swift?", "answer": "Call cancel() on the Task, and check Task.isCancelled or use try Task.checkCancellation() inside:\nlet task = Task {\n for i in 0..<100 {\n try Task.checkCancellation()\n await process(i)\n }\n}\ntask.cancel()\nCooperative cancellation means the task must check for cancellation and stop gracefully [citation:6]."}{"question": "What is an actor in Swift?", "answer": "An actor protects mutable state from concurrent access by serializing access to its methods and properties:\nactor Counter {\n private var value = 0\n func increment() { value += 1 }\n func get() -> Int { value }\n}\nAccess to actor methods is asynchronous from outside:\nlet c = Counter()\nawait c.increment()\nActors prevent data races at compile time [citation:6]."}{"question": "What is the difference between @MainActor and a custom actor?", "answer": "@MainActor is a global actor that serializes access on the main thread, used for UI. A custom actor serializes access on its own executor, not necessarily the main thread:\n@MainActor func updateUI() { }\nactor DataStore { func save() { } }\nUse @MainActor for UI code and custom actors for isolated shared state [citation:6]."}{"question": "What is Sendable in Swift?", "answer": "Sendable marks a type as safe to pass across concurrency domains (threads/actors). Value types with Sendable members are implicitly Sendable; classes must be immutable or use synchronization:\nstruct User: Sendable { let name: String }\nfinal class Cache: @unchecked Sendable { }\nThe compiler enforces Sendable in strict concurrency mode [citation:6]."}{"question": "How do you debug a SwiftUI view?", "answer": "Use Xcode Previews for rapid iteration, and the View Debugger (Debug > View Debugging > Capture View Hierarchy) to inspect layout. Add breakpoints, use print or os_log, and check the console for runtime warnings. The Environment Overrides panel toggles dark mode, Dynamic Type, and accessibility settings [citation:1]."}{"question": "What is the @Binding property wrapper?", "answer": "@Binding creates a two-way connection to state owned by a parent view:\nstruct ChildView: View {\n @Binding var isOn: Bool\n var body: some View {\n Toggle(\"Switch\", isOn: $isOn)\n }\n}\n// Parent:\nChildView(isOn: $parentState)\nIt lets child views mutate parent state without owning it [citation:9]."}{"question": "How do you navigate between views in SwiftUI?", "answer": "Use NavigationStack with NavigationLink:\nNavigationStack {\n NavigationLink(\"Detail\", destination: DetailView())\n}\nFor programmatic navigation, use navigationDestination and a path binding. In iOS 16+, NavigationStack replaces the older NavigationView [citation:9]."}{"question": "What is the @FocusState property wrapper?", "answer": "@FocusState manages keyboard focus:\n@FocusState private var isFocused: Bool\nTextField(\"Name\", text: $name)\n .focused($isFocused)\nYou can set isFocused = true to focus the field programmatically, and read it to dismiss the keyboard [citation:9]."}{"question": "What is a lazy property in Swift?", "answer": "A lazy property is computed only on first access and then stored:\nclass DataLoader {\n lazy var data: [String] = loadData()\n}\nIt is useful for expensive initialization that may not always be needed. lazy cannot be used with let or on structs that are copied frequently [citation:12]."}{"question": "What is the difference between == and === in Swift?", "answer": "== checks value equality when Equatable is implemented. === checks reference identity for class instances:\nlet a = Person(name: \"Alice\")\nlet b = Person(name: \"Alice\")\na == b // true if Equatable compares name\na === b // false, different objects\nUse === to test whether two references point to the same instance [citation:12]."}{"question": "What is Equatable and how do you implement it?", "answer": "Equatable enables == comparison. For simple structs, the compiler synthesizes it:\nstruct Point: Equatable {\n var x: Int\n var y: Int\n}\nlet p1 = Point(x: 1, y: 2)\nlet p2 = Point(x: 1, y: 2)\nprint(p1 == p2) // true\nFor classes or custom logic, implement static func == [citation:12]."}{"question": "What is Hashable and why is it needed?", "answer": "Hashable allows a type to be used in Set and as Dictionary keys. It requires hash(into:) and Equatable:\nstruct User: Hashable {\n var id: UUID\n var name: String\n}\nThe compiler synthesizes Hashable for structs with Hashable members. Hash values must be consistent with equality [citation:12]."}{"question": "What is Codable in Swift?", "answer": "Codable is a typealias for Encodable and Decodable, enabling JSON and property list serialization:\nstruct User: Codable {\n var name: String\n var age: Int\n}\nThe compiler synthesizes coding keys from property names. Use CodingKeys to map custom JSON field names [citation:7]."}{"question": "How do you use CodingKeys to map JSON fields?", "answer": "Define a nested CodingKeys enum:\nstruct User: Codable {\n var name: String\n var userAge: Int\n\n enum CodingKeys: String, CodingKey {\n case name\n case userAge = \"age\"\n }\n}\nThis maps the JSON key \"age\" to the Swift property userAge. Omit cases to exclude properties from coding [citation:7]."}{"question": "What is the @escaping attribute for closures?", "answer": "@escaping marks a closure that may outlive the function call:\nfunc fetch(completion: @escaping (Data) -> Void) {\n DispatchQueue.global().async {\n completion(data)\n }\n}\nNon-escaping closures are the default and are deallocated when the function returns. Escaping closures capture self explicitly in classes [citation:6]."}{"question": "What is a capture list in Swift closures?", "answer": "A capture list controls how variables are captured:\n{ [weak self] in\n self?.doWork()\n}\n{ [unowned self] in\n self.doWork()\n}\nUse [weak self] to avoid retain cycles in escaping closures. unowned assumes self outlives the closure [citation:15]."}{"question": "What is a DispatchQueue in Swift?", "answer": "DispatchQueue manages serial or concurrent execution of tasks:\nlet queue = DispatchQueue(label: \"com.example.work\")\nqueue.async {\n // background work\n DispatchQueue.main.async {\n // update UI\n }\n}\nMain queue is serial and for UI. Global queues are concurrent. Use QoS classes to prioritize work [citation:6]."}{"question": "What is the difference between DispatchQueue.main.async and asyncAfter?", "answer": "DispatchQueue.main.async schedules work to run as soon as possible on the main thread. asyncAfter schedules it after a delay:\nDispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {\n // runs after 1 second\n}\nBoth are non-blocking and return immediately [citation:6]."}{"question": "What is @objc and when is it needed?", "answer": "@objc exposes a Swift declaration to Objective-C runtime, needed for selectors, KVO, and some UIKit target-action patterns:\n@objc func buttonTapped() { }\nbutton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)\nPure SwiftUI code rarely needs it, but UIKit interop does [citation:7]."}{"question": "What is #selector in Swift?", "answer": "#selector references an Objective-C method for target-action:\n#selector(buttonTapped)\nThe method must be marked @objc. It is used with UIControl addTarget and NotificationCenter [citation:7]."}{"question": "What is the difference between frame(width:height:) and frame(maxWidth:maxHeight:)?", "answer": "frame(width:height:) sets a fixed size. frame(maxWidth:maxHeight:) sets a maximum size within which the view can expand:\nText(\"Hello\")\n .frame(maxWidth: .infinity, alignment: .leading)\nUsing maxWidth .infinity makes the view fill available space, common for list rows and buttons [citation:9]."}{"question": "What is the padding modifier in SwiftUI?", "answer": "padding adds space around a view:\nText(\"Hello\")\n .padding() // default padding\n .padding(.horizontal) // horizontal only\n .padding(20) // custom amount\nIt is one of the most common layout modifiers [citation:9]."}{"question": "What is the safeAreaInset modifier?", "answer": "safeAreaInset adds a view that respects the safe area, useful for custom toolbars or banners:\nScrollView { }\n.safeAreaInset(edge: .bottom) {\n Text(\"Bottom banner\")\n}\nContent scrolls behind the inset while remaining visible [citation:9]."}{"question": "What is a LazyVStack and when should you use it?", "answer": "LazyVStack creates views on demand as they scroll into view, improving performance for long lists:\nScrollView {\n LazyVStack {\n ForEach(items) { item in\n ItemRow(item: item)\n }\n }\n}\nUnlike List, LazyVStack does not reuse cells, so use List for very large data sets [citation:9]."}{"question": "What is the onAppear modifier?", "answer": "onAppear runs code when a view appears on screen:\nText(\"Hello\")\n .onAppear {\n print(\"View appeared\")\n }\nIt is commonly used to start data loading. The async alternative is task(priority:) [citation:9]."}{"question": "What is the task modifier in SwiftUI?", "answer": "task runs an async operation when the view appears and cancels it when the view disappears:\nText(\"Data\")\n .task {\n await loadData()\n }\nIt automatically handles cancellation and is preferred over onAppear with Task for async work [citation:6]."}{"question": "What is a Preview in Xcode?", "answer": "A Preview shows a SwiftUI view rendered in the canvas without running the app:\n#Preview {\n ContentView()\n}\nPreviews update live as you edit code, speeding up UI development. You can preview multiple configurations and devices [citation:1]."}{"question": "What is the @EnvironmentObject property wrapper?", "answer": "@EnvironmentObject injects an ObservableObject from the environment:\nclass AppModel: ObservableObject { @Published var user: User? }\n\n// Root view\n.environmentObject(AppModel())\n\n// Child view\n@EnvironmentObject var model: AppModel\nIt avoids passing objects through many layers. The object must be provided by an ancestor or the app crashes [citation:6]."}{"question": "What is the difference between @State and @Binding?", "answer": "@State owns mutable state and manages its storage. @Binding references state owned elsewhere, enabling two-way mutation without ownership:\n@State private var isOn = false\nToggle(\"On\", isOn: $isOn) // $ creates a Binding\nA child view receives @Binding to mutate parent state [citation:9]."}{"question": "What is a generic function in Swift?", "answer": "A generic function works with any type satisfying constraints:\nfunc swapValues<T>(_ a: inout T, _ b: inout T) {\n let temp = a\n a = b\n b = temp\n}\nConstraints use where clauses:\nfunc printAll<T: CustomStringConvertible>(_ items: [T]) { } [citation:4]"}{"question": "What is protocol-oriented programming in Swift?", "answer": "Protocol-oriented programming emphasizes protocols and extensions over class inheritance. Define capabilities as protocols, provide default implementations in extensions, and compose types:\nprotocol Flyable { func fly() }\nextension Flyable {\n func fly() { print(\"Flying\") }\n}\nstruct Bird: Flyable { }\nThis enables flexible composition without deep hierarchies [citation:4]."}{"question": "What is a default protocol implementation?", "answer": "An extension can provide a default implementation for protocol requirements:\nprotocol Greeter {\n func greet() -> String\n}\nextension Greeter {\n func greet() -> String { \"Hello\" }\n}\nstruct English: Greeter { } // uses default\nstruct Spanish: Greeter {\n func greet() -> String { \"Hola\" }\n}\nConforming types can override the default [citation:4]."}{"question": "What is the difference between a protocol and a class?", "answer": "A protocol defines requirements without implementation (except defaults). A class provides concrete implementation and supports inheritance. A type can conform to many protocols but inherit from only one class. Protocols enable composition and testability, while classes enable shared implementation and identity [citation:4]."}{"question": "What is memory management for structs in Swift?", "answer": "Structs are value types and do not use ARC. They are copied on assignment and passed by value, and their memory is managed automatically by the compiler. When a struct contains reference-type properties, those references are retained, so cycles can still occur indirectly [citation:15]."}{"question": "What is a deinitializer in Swift?", "answer": "deinit runs immediately before a class instance is deallocated:\nclass Resource {\n deinit {\n print(\"Deallocated\")\n }\n}\nUse it to release resources not managed by ARC, such as file handles or observers. Structs do not have deinitializers [citation:15]."}{"question": "What is the difference between a stored and computed property?", "answer": "A stored property holds a value in memory. A computed property calculates its value on access and does not store it:\nvar stored = 10\nvar computed: Int { stored * 2 }\nStored properties can be let or var, lazy, or have observers. Computed properties are always var and can be read-only [citation:4]."}{"question": "What is a property observer in Swift?", "answer": "willSet and didSet observe changes to a stored property:\nvar score = 0 {\n willSet { print(\"Changing to \\(newValue)\") }\n didSet { print(\"Changed from \\(oldValue)\") }\n}\nThey are called on every assignment, including within initializers? No — observers do not run during initialization [citation:12]."}{"question": "What is the @autoclosure attribute?", "answer": "@autoclosure wraps an expression in a closure automatically, delaying evaluation:\nfunc log(_ message: @autoclosure () -> String) {\n print(message())\n}\nlog(\"Expensive: \\(compute())\")\nThe expression is not evaluated unless message() is called. The ?? operator uses it for the default value [citation:3]."}{"question": "How do you check if an Optional is nil in Swift?", "answer": "Compare to nil directly:\nif optionalValue == nil { }\nOr use optional binding:\nif optionalValue == nil { } else { }\nFor collections, check isEmpty. Avoid comparing an Optional to nil when you can use if let or guard let for clarity [citation:3]."}{"question": "What is the difference between Int(\"42\") and Int(\"abc\")?", "answer": "Int(\"42\") returns Optional(42) because the string is a valid integer. Int(\"abc\") returns nil because the string cannot be parsed:\nlet a = Int(\"42\") // Int? = 42\nlet b = Int(\"abc\") // Int? = nil\nYou must unwrap the result before using it as an Int [citation:3]."}{"question": "How do you sort an array in Swift?", "answer": "Use sorted() for a new sorted array or sort() for in-place:\nlet numbers = [3, 1, 2]\nlet ascending = numbers.sorted()\nvar mutable = [3, 1, 2]\nmutable.sort(by: >)\nprint(mutable) // [3, 2, 1]\nFor custom types, pass a closure or conform to Comparable [citation:12]."}{"question": "How do you filter an array in Swift?", "answer": "Use filter with a predicate:\nlet numbers = [1, 2, 3, 4, 5]\nlet evens = numbers.filter { $0 % 2 == 0 }\nprint(evens) // [2, 4]\nfilter returns a new array. Combine with map and reduce for data pipelines [citation:12]."}{"question": "How do you map an array in Swift?", "answer": "Use map to transform each element:\nlet numbers = [1, 2, 3]\nlet squares = numbers.map { $0 * $0 }\nprint(squares) // [1, 4, 9]\nflatMap flattens nested results, and compactMap removes nil values:\nlet strings = [\"1\", \"a\", \"3\"]\nlet ints = strings.compactMap { Int($0) } // [1, 3] [citation:12]"}{"question": "What is the reduce function in Swift?", "answer": "reduce combines all elements into a single value:\nlet numbers = [1, 2, 3, 4]\nlet sum = numbers.reduce(0, +)\nprint(sum) // 10\nlet joined = [\"a\", \"b\"].reduce(\"\") { $0 + $1 }\nThe first argument is the initial value, and the closure combines the accumulator with each element [citation:12]."}{"question": "What is the difference between map and compactMap?", "answer": "map returns an array with the same count, even if the transformation returns nil (resulting in Optional values). compactMap unwraps Optionals and removes nil results:\nlet strings = [\"1\", \"x\", \"3\"]\nlet mapped = strings.map { Int($0) } // [Int?] = [1, nil, 3]\nlet compacted = strings.compactMap { Int($0) } // [1, 3]\nUse compactMap when the transformation can fail [citation:12]."}{"question": "What is a Set in Swift?", "answer": "A Set is an unordered collection of unique Hashable elements:\nvar ids: Set<Int> = [1, 2, 3]\nids.insert(2) // already present\nids.contains(1) // true\nids.remove(3)\nSets provide O(1) average membership checks. Use them to deduplicate arrays:\nlet unique = Array(Set(array)) [citation:12]"}{"question": "What is a Dictionary in Swift?", "answer": "A Dictionary stores key-value pairs with unique Hashable keys:\nvar scores = [\"Alice\": 90, \"Bob\": 85]\nscores[\"Charlie\"] = 88\nif let alice = scores[\"Alice\"] {\n print(alice)\n}\nSubscript access returns an Optional. Iterate with for (key, value) in scores [citation:12]."}{"question": "What is the difference between Array and ArraySlice?", "answer": "An Array is a standalone collection. An ArraySlice is a view into a portion of an array with shared storage and zero-based indexing relative to the slice:\nlet arr = [0, 1, 2, 3, 4]\nlet slice = arr[2...4] // ArraySlice [2, 3, 4]\nprint(slice[2]) // 2, slice indices start at 2\nConvert with Array(slice) for independent storage [citation:12]."}{"question": "What is a tuple in Swift?", "answer": "A tuple groups multiple values into a single compound value:\nlet person = (name: \"Alice\", age: 30)\nprint(person.name)\nprint(person.1)\nlet (name, age) = person\ndefer a value\nTuples are lightweight and useful for multiple return values, but they are not suited for complex data modeling [citation:12]."}{"question": "What is the defer statement in Swift?", "answer": "defer runs code when the current scope exits, regardless of how it exits:\nfunc readFile() {\n let file = open()\n defer { close(file) }\n // use file; close runs at return\n}\nDefers run in reverse order of declaration. They are useful for cleanup in functions with multiple exit points [citation:3]."}{"question": "What is a where clause in Swift?", "answer": "where adds constraints to generics, loops, and switch cases:\nfunc process<T>(_ items: [T]) where T: Equatable { }\nfor i in 0..<10 where i % 2 == 0 { }\nswitch value {\ncase let x where x > 0: print(\"positive\")\ndefault: break\n}\nIt improves readability by keeping constraints near the declaration [citation:4]."}{"question": "What is the @unknown default case in Swift?", "answer": "@unknown default handles future cases of a non-frozen enum without a compiler warning:\nswitch direction {\ncase .north: break\ncase .south: break\n@unknown default: break\n}\nIt signals that the default handles cases not known at compile time, useful for library enums [citation:4]."}{"question": "What is a variadic parameter in Swift?", "answer": "A variadic parameter accepts zero or more values of a type:\nfunc sum(_ numbers: Int...) -> Int {\n numbers.reduce(0, +)\n}\nprint(sum(1, 2, 3))\nInside the function, the parameter is an array. A function can have at most one variadic parameter [citation:4]."}{"question": "What is inout in Swift?", "answer": "inout allows a function to modify a parameter and have the change persist:\nfunc increment(_ value: inout Int) {\n value += 1\n}\nvar x = 5\nincrement(&x)\nprint(x) // 6\nThe argument must be a mutable variable, and you pass it with &. inout is similar to ref in C# [citation:4]."}{"question": "How do you use URLSession with async/await?", "answer": "iOS 15+ provides async variants:\nlet (data, response) = try await URLSession.shared.data(from: url)\nlet (data2, response2) = try await URLSession.shared.data(for: request)\nHandle errors with do/try/catch. This replaces completion handlers and integrates with Swift concurrency [citation:6]."}{"question": "What is the main thread and why is it important in iOS?", "answer": "The main thread handles UI events and rendering. Updating UI from a background thread causes crashes or undefined behavior. Use @MainActor or DispatchQueue.main.async to return to the main thread after background work [citation:6]."}{"question": "What is a ViewModel in SwiftUI?", "answer": "A ViewModel is an ObservableObject that holds view state and business logic, keeping views declarative:\n@MainActor\nclass CounterViewModel: ObservableObject {\n @Published private(set) var count = 0\n func increment() { count += 1 }\n}\nViews observe it with @StateObject or @ObservedObject. This separates UI from logic and improves testability [citation:6]."}{"question": "How do you test a ViewModel in Swift?", "answer": "Instantiate the ViewModel and call methods, asserting published state:\nfunc testIncrement() {\n let vm = CounterViewModel()\n vm.increment()\n XCTAssertEqual(vm.count, 1)\n}\nUse @MainActor on the test class if the ViewModel is main-actor isolated. Mock dependencies for async tests [citation:10]."}{"question": "What is the difference between a unit test and a UI test?", "answer": "Unit tests verify small pieces of logic in isolation, such as ViewModels and utilities, and run fast. UI tests drive the app through XCUITest, verifying user flows and rendering, and run slower on simulators or devices. Both are part of an XCTest suite [citation:10]."}{"question": "What is a scheme in Xcode?", "answer": "A scheme defines how Xcode builds, runs, tests, profiles, analyzes, and archives a target. It specifies the build configuration, executable, arguments, and environment variables. Shared schemes are committed to version control for consistent CI behavior [citation:1]."}{"question": "What is the App Store submission process for an iOS app?", "answer": "Archive the app in Xcode (Product > Archive), validate it with App Store Connect, upload the build, fill in metadata, screenshots, and privacy details, then submit for review. Apple reviews the app against guidelines, and once approved, you release it manually or automatically [citation:1]."}{"question": "What is the difference between `include` and `require`?", "answer": "`include` produces a warning if the file is missing but continues execution. `require` produces a fatal error and stops execution. `include_once` and `require_once` ensure the file is included only once, preventing redeclaration errors."}{"question": "How do you handle errors in PHP?", "answer": "Use `try-catch` blocks for exceptions. Configure error reporting with `error_reporting()` and `ini_set('display_errors', 0)` in production. Log errors to a file using `error_log()`. Custom error handlers can be set with `set_error_handler()`."}{"question": "What is an exception in PHP?", "answer": "An exception is an object representing an error condition. Throw one with `throw new Exception('Message')`. Catch it with `catch (Exception $e)`. Exceptions allow graceful error handling and separation of error logic from business logic."}
dataset_3.jsonl+117