Swift Playground

RSS for tag

Learn and explore coding in Swift through interactive learning experiences on the Swift Playground app for iPadOS and macOS.

Posts under Swift Playground tag

94 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Does Swift Playground Support Custom Code Snippets Like Xcode?
While demonstrating Swift Playground to my students, I noticed that, unlike Xcode, it doesn’t seem possible to predefine or insert custom code snippets. In Xcode, we can easily create and reuse our own code snippets to improve teaching and development efficiency, but I couldn’t find a similar feature in Swift Playground. Is there currently a way to predefine or insert custom code snippets in Swift Playground? Are there any recommended workarounds, or plans to support this feature in the future? Any suggestions or insights would be greatly appreciated.
1
0
30
Jul ’25
Swift Playground crashes
I'm trying to use the new #Playground feature in Xcode, but it keeps crashing in the canvas. I am testing on Xcode 26.0 beta 4, on both macOS 15 and macOS26 beta 4. How do I figure out what's going on? I also have a few SwiftUI previews in my project, which also crashes if I try to preview them. They're not in any active tab right now in Xcode. But the #Playground feature still doesn't work. I also don't get a crash when working on a #Playground in a different project. I've tried cleaning out Derived Data and restarting the Mac / Xcode, all with no avail. How do I track down what's causing this? Do previews and playground run on the same engine? System Integrity Protection: enabled Triggered by Thread: 0 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: Namespace OBJC, Code 1, Thread 0 Crashed: 0 libsystem_kernel.dylib 0x100634ad0 __abort_with_payload + 8 1 libsystem_kernel.dylib 0x100659dc0 abort_with_payload_wrapper_internal + 100 2 libsystem_kernel.dylib 0x100659d5c abort_with_reason + 28 3 libobjc.A.dylib 0x18009bd08 _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 112 4 libobjc.A.dylib 0x18009bc98 _objc_fatal(char const*, ...) + 28 5 libobjc.A.dylib 0x18008be14 lookUpImpOrForward + 580 6 libobjc.A.dylib 0x180072f00 _objc_msgSend_uncached + 64 7 ??? 0x340a44048 ??? 8 CJournal 0x1001c54c4 __debug_blank_executor_run_user_entry_point + 152 9 PreviewsInjection 0x241623bf4 0x2415ff000 + 150516 10 PreviewsInjection 0x24162481c 0x2415ff000 + 153628 11 PreviewsInjection 0x241624740 __previews_injection_run_user_entrypoint + 12 12 XOJITExecutor 0x25543ad48 __xojit_executor_run_program_wrapper + 1460 13 XOJITExecutor 0x25543725c 0x255435000 + 8796 14 PreviewsInjection 0x24162468c 0x2415ff000 + 153228 15 CJournal 0x1001c4c7c __debug_blank_executor_main + 996 16 ??? 0x1003e13d0 ??? 17 dyld 0x100218924 start + 6400
2
1
106
Jul ’25
Liquid Glass Error
Hello everyone. I'm getting an error in my code and I don't know why. Can someone explain it to me? import SwiftUI struct ContentView: View{ var body: some View{ VStack { Button {} label: { Text("Click Me") } .buttonStyle(.glass) .frame(width: 200, height: 200) } } } The error is as follows: Reference to member 'glass' cannot be resolved without a contextual type Thanks for your help
1
0
189
Jul ’25
Core Data stack in #Playground
I'm using the #Playground macro in Xcode 26.0, running on macOS 26.0. I can get the basics working, but I don't understand how it hooks into the rest of the app, like the App Delete or the Core Data stack. Do we have to create a new Core Data stack, like for SwiftUI Previews, or can it hook into the stack from the main app (if so, how)?
1
0
113
Jul ’25
Main actor-isolated property can not be referenced
Hello I'm getting this error in my code and I don't know why. Can somebody explain this or point me at a help article. import UIKit var greeting = "Hello, playground" let imageView = UIImageView() imageView.image = UIImage(named: "image") Utils.getImageSize(view: imageView) class Utils { static func getImageSize(view imageView: UIImageView) { let image = imageView.image print("Image size = \(image?.size ?? CGSize.zero)") } } The error is as follows: Cheers Murray
4
0
125
Jul ’25
Beginner Question - Local SPM Folder Structure
Hi there, I am working on an iOS mobile app, with a MVVM architecture and created an SPM folders for my DesignSystem, CoreKit, UnityBridge, and VoicePipeline. I added the packages locally, and dragged them into the project. Is working this way recommended? Or not? Should all the SPM folders I listed above be used this way, or should only some? New to this, unsure what is best. I do plan on sharing my code with other devs to work on. I thought this made sense, but if i did it the other way I was unsure how I would share the packages what is a best practice. Thanks so much!
1
0
67
Jul ’25
Issue with #Playground and Foundation Model
Hi all, I’m encountering an issue when trying to run Apple Foundation Models in a blank project targeting iOS 26. Below are the details: Xcode: Latest version with iOS 26 SDK macOS: macOS 26 Tahoe (installed on main disk) Mac: 16” MacBook Pro with M2 Pro chip Apple Intelligence: Available and functional on this machine Problem: I created a new blank iOS project, set the deployment target to iOS 26, and ran the following minimal code using Foundation Models. However, I get no response at all in the output - not even an error. The app runs, but the model does not produce any output. #Playground { let session = LanguageModelSession() let response = try await session.respond(to: "Tell me a story") } Then, I tried to catch an error with this code: #Playground { let session = LanguageModelSession() do { let response = try await session.respond(to: "Tell me a story") print(response) } catch { print("Failed to get response:", error) } print("This line, never gets executed") } And got these results: I’ve done further testing and discovered something important: I tried running the Code Along sample project, and there the #Playground macro worked without issues. The only significant difference I noticed was the Canvas run destination: In my original project, I was using iPhone 16 Pro (iOS 26) as the run target in Canvas. Apple Intelligence was enabled on the simulator, but no response was returned when executing the prompt. In the sample project, the Canvas was running on My Mac. I attempted to match that setup, but at first, my destination was My Mac (Designed for iPad), which still didn’t work. The macro finally executed properly once I switched to My Mac (AppKit). So the question is ... it seems that for now, Foundation Models and the #Playground macro only run correctly when the canvas or destination is set to “My Mac (AppKit)”?
7
0
431
Jul ’25
Checking the contents of a TextField variable method not working
Hoping someone can help me with this… The error is… Generic parameter ‘/‘ cannot be inferred. .multilineTextAlignment(.center) .onAppear(perform: { var checkFirstCardLatitude = cards.firstCardLatitude let charArray = Array(checkFirstCardLatitude) let allowed: [Character] = ["-", ".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] for char in charArray { if char != allowed { cards.firstCardLatitude = "000.000000" // Reset Text Field } } })
26
0
298
May ’25
iPhone Doesn't Support App's Architectures (SwiftPM)
Hi, after recently upgrading Xcode to the latest version, I encountered a new bug that prevented me from building the app on my iPhone. Puzzlingly, the app still builds and runs fine on a simulator. Because I am working with a Swift Playground file, the option is not available to simply change the architecture setting. I found a similar setting within the Schemes, but after trying a combination of different architecture settings, the app still doesn't build properly. I noticed the BuildAction seemed to be changing, so I believe that the setting was properly affecting the Architecture setting. Even with a separate dummy test project (SwiftPM), I still ran into the same issues. I updated my iPhone OS to the latest version as well after initially encountering the bug. I'm wondering if anybody is running into the same issues, and if any solutions have been found.
3
0
96
Apr ’25
LLDB RPC server crash in Xcode 16.3
Created a new project in Xcode 16.3. While adding breakpoints app is crashing every time in Xcode and playground both. Tried with swift 5 and swift 6 getting same error. Crash reason : Couldn't find the Objective-C runtime library in loaded images. Message from debugger: The LLDB RPC server has crashed. You may need to manually terminate your process lldb-rpc-server-2025-04-14-092736.txt
4
6
305
May ’25
Issue with calculating the distance between two points on a map
I have an error issue that I haven’t been able to solve despite doing extensive research. In fact the similar examples I have found so far have been educational but I have not been able to make work. The example below I am hoping will be easy to fix as it is only producing errors with one line of code… import SwiftUI import CoreLocation var currentLon = Double() var currentLat = Double() extension CLLocation { class func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance { let from = CLLocation(latitude: from.latitude, longitude: from.longitude) let to = CLLocation(latitude: to.latitude, longitude: to.longitude) return from.distance(from: to) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { currentLon = (locations.last?.coordinate.longitude)! currentLat = (locations.last?.coordinate.latitude)! }/*⚠️ Not sure if this function will work? (Update User Location coordinates on the move?)*/ } struct Positions: Identifiable { let id = UUID() let name: String let latitude: Double let longitude: Double var coordinate: CLLocationCoordinate2D { CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } } struct GameMapView: View { let from = CLLocationCoordinate2D(latitude: currentLon, longitude: currentLat) let to = CLLocationCoordinate2D(latitude: thisCardPositionLongitude, longitude: thisCardPositionLongitude) let distanceFrom = from.distance(from: to) /*⚠️ ERRORS: 1. Cannot use instance member 'from' within property initializer; property initializers run before 'self' is available. 2. Cannot use instance member 'to' within property initializer; property initializers run before 'self' is available. 3. Value of type 'CLLocationCoordinate2D' has no member 'distance'. */ @State private var region = MKCoordinateRegion( center: CLLocationCoordinate2D( latitude: thisCardPositionLatitude, longitude: thisCardPositionLongitude), span: MKCoordinateSpan( latitudeDelta: 0.0001, longitudeDelta: 0.0001) ) var body: some View { Map(coordinateRegion: $region, showsUserLocation: true, annotationItems: locations){ place in MapMarker(coordinate: place.coordinate,tint: Color.accentColor) } .edgesIgnoringSafeArea(.all) VStack { Print("Distance from Location: \(distanceFrom)") font(.largeTitle) padding() }
1
0
86
Apr ’25
Piece of code in Playground that reliably crashes lldb server
Dare anyone try the following code in any Playground: // Define a model that conforms to Codable struct User: Codable { var name: String var age: Int var email: String? } // JSON data (as a string for demonstration) let jsonString = """ { "name": "John Doe", "age": 30, "email": "john@example.com" } """ // Convert the JSON string to Data if let jsonData = jsonString.data(using: .utf8) { do { // Parse the JSON data into the User model let user = try JSONDecoder().decode(User.self, from: jsonData) print("Name: \(user.name), Age: \(user.age), Email: \(user.email ?? "N/A")") } catch { print("Error decoding JSON: \(error)") } } I tested with Xcode 16.2 and latest 16.3, it reliably crashes the lldb server!
6
1
171
Apr ’25
‘Keep going with apps’ Crash during Creature Add steps
Hello fellow Techies! I am currently doing the Swift Playgrounds “Keep Going with Apps” on my iPad Pro. Everything has been going as designed until I got to the ‘Add and Delete Creatures‘ module. The lesson concludes with being able to add a creature to your list in the CreatureZoo. When you run the app from the playground, you can fill out the fields and tap ‘Add’ and that is when the app dims and after 5 seconds I get the notification that the app has an unknown crash. I have reviewed the lessons leading up to it, but I can’t find anything wrong. (Full Disclosure: I really have no clue what I am looking at some of time.) Has anyone else ran into this? `import SwiftUI import Guide struct CreatureEditor: View { //#-learning-code-snippet(defineVariablesCreatureEditor) //#-learning-code-snippet(environmentValue) @State var newCreature : Creature = Creature(name: "", emoji: "") @EnvironmentObject var data : CreatureZoo @Environment(.dismiss) var dismiss var body: some View { SPCAssessableGroup(view: self) { VStack(alignment: .leading) { Form { Section("Name") { //#-learning-code-snippet(addACreatureEditorTextField) TextField("What is your monster's name?", text: $newCreature.name) } Section("Emoji") { TextField("What does your monster look like?", text: $newCreature.emoji) } Section("Creature Preview") { CreatureRow(creature: newCreature) } } } .toolbar { ToolbarItem { Button("Add") { data.creatures.append(newCreature) dismiss() } } } //#-learning-code-snippet(addButtonToToolbar) } } } struct CreatureEditor_Previews: PreviewProvider { static var previews: some View { NavigationStack() { CreatureEditor().environmentObject(CreatureZoo()) } } }’
4
0
198
Mar ’25
Swift Playground 4.6 - App Fails to Run with import AppIntent
Hi everyone, I’ve been developing an app using Swift Playgrounds, and it was working fine in version 4.5. However, after updating to Swift Playground 4.6, the app no longer runs. After some testing, I found that the issue occurs when import AppIntent is included. Here’s a simple example: import SwiftUI //import AppIntents // <- If this line is included, Preview and Run fail. @main struct MyApp: App { var body: some Scene { WindowGroup { Image(systemName: "globe") .imageScale(.large) .foregroundColor(.accentColor) Text("Hello, world!") } } } Has anyone else encountered this issue? Thanks!
2
1
252
Mar ’25
Swift Playgrounds 4.6 removes support for libraries?
I had several library projects that were working in Swift Playgrounds < 4.6 but I get several duplicate compilation errors and previews will not build in Swift Playgrounds > 4.6. Does anyone know how to fix this issue? Example project: This project builds and runs fine under Swift Playgrounds 4.5.1 however it will not run complaining multiple commands produce generated output files under Swift Playgrounds 4.6.1, 4.6.2, and 4.6.3. https://github.com/kudit/Compatibility Download this repository and add the extension ".swiftpm" to the folder and double click to open in Swift Playgrounds. If running on earlier Swift Playgrounds you can see there are no errors and previews work great (on both macOS and iPadOS versions of Swift Playgrounds 4.5.x). However, on Swift Playgrounds 4.6.x, previews will not display. Are embedded libraries not support anymore? This would be very disappointing. I posted this as a Feedback weeks ago with no response: FB16509699
4
0
323
Jun ’25
PlaygroundSupport no longer available for Playground apps
In Swift Playground 4.6.2 the package PlaygroundSupport is no longer available to Playground apps. The following test previously permitted apps run in the Playground vs compiled in XCode to support different behavior: #if canImport(PlaygroundSupport) container = NSPersistentContainer(name: "myApp", managedObjectModel: Self.createModel()) #else container = NSPersistentCloudKitContainer(name: "myApp") #endif Since Swift Playground 4.6.2 the PlaygroundSupport package is no longer available for app projects in Playgrounds. Is there a different compile type test which can be used to differentiate compilation for Swift Playground apps ? I am currently having to use a runtime workaround (below) but would prefer a compile time test is an alternative is available. public static var inPlayground: Bool { if Bundle.allBundles.contains(where: { ($0.bundleIdentifier ?? "").contains("swift-playgrounds") }) { return true } else { return false } }
1
1
426
Feb ’25
Bundle Display Name Swift Playgrounds
I am attempting to use the AVSpeechSynthesizer to include text to speech in my Swift Playgrounds project, but when I attempt to use it on my IPhone i get the following errors: It works just fine on the simulator, but no audio is produced when I run it on-device. Is there a way to set this "bundle display name" within Swift Playgrounds, or are there any workarounds? My code: import AVFoundation class Speaker { let synthesizer = AVSpeechSynthesizer() func speak() { let utterance = AVSpeechUtterance(string: "Test, I am the speaker") synthesizer.speak(utterance) } }
1
1
361
Feb ’25