iOS
Come comprendi il termine concorrenza strutturata in Swift? Task.detached si adatta a questo concetto?
Parlami dell'uso di SwiftUI nel progetto — qual è la politica, quante schermate sono scritte in SwiftUI
Quando e come avviene l'annullamento utilizzando DispatchQueue con WorkItem e chiamando cancel()?
Perché hai creato metodi separati load e getLastCities, e cosa dovrebbe succedere se getLastCities viene chiamato prima che i dati siano stati caricati?
Quanto ti aiutano gli strumenti di IA (Cursor, Proxyman, ecc.) a essere più produttivo al lavoro?
Perché hai scelto un dizionario come memorizzazione nella cache?
import UIKit protocollo CacheProtocol { associatedtype Value func setValue(_ value: Value?, forKey key: String) func value(forKey key: String) -> Value? func fetchValue(forKey key: String, completion: @escaping (Value?) -> Void) }
// Scrive `data` in un file chiamato `file`. func writeData(_ data: Data, to file: String) { let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let fileURL = documentDirectoryURL.appendingPathComponent(file) try? data.write(to: fileURL) } // Rimuove il file chiamato `file`. func remove(file: String) { let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let fileURL = documentDirectoryURL.appendingPathComponent(file) try? FileManager.default.removeItem(at: fileURL) } // Legge `Data` da un file chiamato `file`. Se il file non esiste, ritorna `nil`. func readData(from file: String) -> Data? { let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let fileURL = documentDirectoryURL.appendingPathComponent(file) return try? Data(contentsOf: fileURL) } final class DiskCache<T>: CacheProtocol { func setValue(_ value: T?, forKey key: String) { } func getValue(forKey key: String) -> T? { } func fetchValue(forKey key: String, completion: @escaping (T?) -> Void) { } }
protocollo CacheProtocol { associatedtype Value func setValue(_ value: Value?, forKey key: String) func getValue(forKey key: String) -> Value? func fetchValue(forKey key: String, completion: @escaping (Value?) -> Void) } final class Cache<T>: CacheProtocol { private var storage: [String: T] = [:] func setValue(_ value: T?, forKey key: String) { storage[key] = value } func getValue(forKey key: String) -> T? { return storage[key] } func fetchValue(forKey key: String, completion: @escaping (T?) -> Void) { let value = storage[key] completion(value) } } import XCTest final class CacheTests: XCTestCase { override func setUp() { super.setUp() } func testSetAndGetValue() { let cache = Cache<String>() let key: String = "key" let value: String = "value" cache.setValue(value, forKey: key) XCTAssertEqual(cache.getValue(forKey: key), value) cache.setValue(nil, forKey: key) XCTAssertTrue(cache.getValue(forKey: key) == nil) } } CacheTests.defaultTestSuite.run()
classe finale Cache<T>: CacheProtocol { func getValue(forKey key: String) -> T? { return storage[key] } func fetchValue(forKey key: String, completion: @escaping (T?) -> Void) { let value = storage[key] completion(value) } } classe finale CacheTests: XCTestCase { override func setUp() { super.setUp() } func testSetAndGetValue() { let cache = Cache<String>() let key: String = "key" let value: String = "value" cache.setValue(value, forKey: key) XCTAssertEqual(cache.getValue(forKey: key), value) cache.setValue(nil, forKey: key) XCTAssertTrue(cache.getValue(forKey: key) == nil) } func testCompletion() { } } CacheTests.defaultTestSuite.run()
Auto -> Compito -> (forte) Auto .... Indietro -> View desinit -> View model deinit?
classe finale NetworkService { func request<Response: Decodable, Body: Encodable>(urlString: String, method: HTTPMethod, body: Body? = nil, headers: [String: String] = [:], query: [String: String] = [:]) async throws -> Response { guard var components = URLComponents(string: urlString) else { throw Errors.invalidUrl } if !query.isEmpty { components.queryItems = query.map { URLQueryItem(name: $0.key, value: $0.value) } } guard let url = components.url else { throw Errors.invalidQuery } var request = URLRequest(url: url) request.httpMethod = method.rawValue headers.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) } if let body, method == .post { request.httpBody = try encoder.encode(body) // ? } let (data, response) = try await session.data(for: request) guard let httpResponse = response as? HTTPURLResponse else { throw Errors.invalidResponse } guard (200...299).contains(httpResponse.statusCode) else { throw Errors.httpStatus(httpResponse.statusCode) } return try decoder.decode(Response.self, from: data) } }
Come daresti priorità ai problemi identificati se il progetto deve andare in produzione tra un'ora?
Spiega la differenza tra una cache in memoria e una cache su disco.
Perché usare una classe finale invece di una classe per l'implementazione della cache?
enum HTTPMethod: String { case post = "POST" } enum Errors: Error { case invalidUrl case invalidQuery case invalidResponse case httpStatus(Int) } protocol MyDecoder { func decode<T: Decodable>(_: _ type: T.Type, from data: Data) throws -> T } final class NetworkService { private let session: URLSession private let encoder = JSONEncoder() private let decoder: MyDecoder init( session: URLSession = .shared, decoder: MyDecoder ) { self.session = session self.decoder = decoder } func request<Response: Decodable, Body: Encodable>( urlString: String, method: HTTPMethod, body: Body? = nil, headers: [String: String] = [:], query: [String: String] = [:] ) async throws -> Response { guard var components = URLComponents(string: urlString) else { throw Errors.invalidUrl } if !query.isEmpty { components.queryItems = query.map { URLQueryItem(name: $0.key, value: $0.value) } } guard let url = components.url else { throw Errors.invalidQuery } var request = URLRequest(url: url)
// Servizio che invia richieste (get/post), url, formazione della richiesta in base alla semantica (decode/encode)