Swift Meets Artificial Intelligence: Why It Matters Right Now
\n\nImagine: you're writing an iOS app, and suddenly your user can simply ask it: "How to cook carbonara pasta?" — and get not a Wikipedia link, but a live, detailed answer. Or ask: "Write a letter to the boss about moving the deadline" — and in a second, the draft is ready. Sounds like magic? No, it's Swift + ChatGPT.
\n\nIn 2024, integrating language models into mobile apps is no longer the domain of giants. Now any Swift developer can add artificial intelligence to their app in an evening. And today I'll show you how to do it — with real code, no fluff, and an understanding of what's happening under the hood.
\n\nBy the way, if you're just starting your journey with Swift and want to dive deeper into the basics, PythonLib is a great place to brush up on the fundamentals before diving into AI. Now — let's get to work.
\n\nStep 1. Setting Up the Environment: What You Need to Work with ChatGPT in Swift
\n\nBefore writing code, let's make sure you have everything you need. You will need:
\n\n- \n
- Xcode 15.0 or newer (preferably the latest version) \n
- iOS 16.0+ (to use
async/awaitwithout workarounds) \n - An API key from OpenAI (register at platform.openai.com, create a key) \n
- A library for networking — we'll use
URLSession, so no third-party dependencies are needed \n
Important tip: never store the API key directly in the code. Use .xcconfig files or a server proxy. In the examples, I'll show how to read the key from Info.plist, but in production, be sure to encrypt it or use a backend.
Step 2. Creating the Request Structure for ChatGPT
\n\nChatGPT uses the OpenAI API, which accepts JSON and returns the model's response. Let's create a simple but functional structure for sending messages.
\n\nData Models
\n\n// Message model\nstruct Message: Codable {\n let role: String // "system", "user" or "assistant"\n let content: String\n}\n\n// Request model\nstruct ChatGPTRequest: Codable {\n let model: String\n let messages: [Message]\n let temperature: Double?\n}\n\n// Response model\nstruct ChatGPTResponse: Codable {\n struct Choice: Codable {\n let message: Message\n }\n let choices: [Choice]\n}\n\n\nNote the temperature — this is the creativity parameter. A value of 0.0 makes responses strict and factual, 1.0 makes them creative. For a chatbot, set it to 0.7, for idea generation — 0.9.
Service for Working with the API
\n\nclass ChatGPTService {\n \n private let apiKey: String\n private let baseURL = "https://api.openai.com/v1/chat/completions"\n \n init() {\n // Read the key from Info.plist (for testing only!)\n guard let key = Bundle.main.object(forInfoDictionaryKey: "OPENAI_API_KEY") as? String else {\n fatalError("API Key not found")\n }\n self.apiKey = key\n }\n \n func sendMessage(_ text: String) async throws -> String {\n let messages = [\n Message(role: "system", content: "You are a helpful iOS developer assistant. Answer briefly, in Russian."),\n Message(role: "user", content: text)\n ]\n \n let requestBody = ChatGPTRequest(\n model: "gpt-3.5-turbo",\n messages: messages,\n temperature: 0.7\n )\n \n var request = URLRequest(url: URL(string: baseURL)!)\n request.httpMethod = "POST"\n request.setValue("application/json", forHTTPHeaderField: "Content-Type")\n request.setValue("Bearer \\(apiKey)", forHTTPHeaderField: "Authorization")\n request.httpBody = try JSONEncoder().encode(requestBody)\n \n let (data, _) = try await URLSe