I clicked the “Get” button in the Swift tutorial, and it started displaying a circular progress bar. However, when the progress bar was full, it did not show that I could use this tutorial, but still display “Get”.
Device: iPad (7th)
System: iPadOS 18.3.2
App Version: 4.6.4
Swift Playground
RSS for tagLearn 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
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
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)?
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.
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
Can anyone help me why i cannot move on?
I thought I had finished the instrcutions. However, it seems that i missed something that I didnt find out.
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
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
In the play ground I'm trying to bias my LanguageModel to use a tool I registered, but I don't see it actually calling the tool. I'm following the developer video on landmarks itinerary generation tutorial almost verbatim. Is this a prompt engineering thing I'm missing? Or is it possible that I'm injecting my tool wrong?
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!
Topic:
Developer Tools & Services
SubTopic:
Xcode
Tags:
Swift Packages
Swift
Swift Playground
Education
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)”?
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
Topic:
Developer Tools & Services
SubTopic:
Swift Playground
Tags:
Swift Packages
Swift Playground
Playground Support
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
}
}
})
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
Topic:
Developer Tools & Services
SubTopic:
Xcode
Tags:
Swift Playground
Xcode
Playground Support
LLDB
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.
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()
}
Topic:
App & System Services
SubTopic:
Maps & Location
Tags:
Swift Playground
Swift
MapKit
Maps and Location
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!
Has anyone been able to successfully use MusicCatalogSearchRequest in a playgrounds app?
I have configured my playground similar to a regular app: app id with automatic music token generation turned on, music access authorized within the app itself, but whenever I query MusicCatalogSearchRequest I get an error thrown with .developerTokenRequestFailed.
Considering musickit is restricted in the sim, it would not surprise me if it was the same in playgrounds but it would be super helpful if I could prototype with musickit in playgrounds 4!
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())
}
}
}’
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!
Following code crashes (sigsegv in lldb-rpc-server) when run as swift 6, but runs correctly when run as swift 5 (from "Metal by tutorials"):
import PlaygroundSupport
import MetalKit
print("start")
guard let device = MTLCreateSystemDefaultDevice() else {
fatalError("GPU is not supported")
}
let frame = CGRect(x: 0, y: 0, width: 600, height: 600)
let view = MTKView(frame: frame, device: device)
view.clearColor = MTLClearColor(red: 1, green: 1, blue: 0.8, alpha: 1)
let allocator = MTKMeshBufferAllocator(device: device)
let mdlMesh = MDLMesh(sphereWithExtent: [0.75,0.75,0.75], segments: [100, 100], inwardNormals: false, geometryType: .triangles, allocator: allocator)
let mesh = try MTKMesh(mesh: mdlMesh, device: device)
guard let commandQueue = device.makeCommandQueue() else {
fatalError("Could not create a command queue")
}
let shader = """
#include <metal_stdlib>
using namespace metal;
struct VertexIn {
float4 position [[attribute(0)]];
};
vertex float4 vertex_main(const VertexIn vertex_in [[stage_in]])
{
return vertex_in.position;
}
fragment float4 fragment_main() {
return float4(1, 0, 0, 1);
}
"""
print("A")
let library = try device.makeLibrary(source: shader, options: nil)
let vertexFunction = library.makeFunction(name: "vertex_main")
let fragmentFunction = library.makeFunction(name: "fragment_main")
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
pipelineDescriptor.vertexFunction = vertexFunction
pipelineDescriptor.fragmentFunction = fragmentFunction
print("X")
pipelineDescriptor.vertexDescriptor = MTKMetalVertexDescriptorFromModelIO(mesh.vertexDescriptor)
let pipelineState = try device.makeRenderPipelineState(descriptor: pipelineDescriptor)
guard let commandBuffer = commandQueue.makeCommandBuffer(),
let renderPassDescriptor = view.currentRenderPassDescriptor,
let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor)
else {
fatalError()
}
renderEncoder.setRenderPipelineState(pipelineState)
renderEncoder.setVertexBuffer(mesh.vertexBuffers[0].buffer, offset: 0, index: 0)
guard let submesh = mesh.submeshes.first else {
fatalError()
}
renderEncoder.drawIndexedPrimitives(type: .triangle, indexCount: submesh.indexCount, indexType: submesh.indexType, indexBuffer: submesh.indexBuffer.buffer, indexBufferOffset: 0)
renderEncoder.endEncoding()
guard let drawable = view.currentDrawable else {
fatalError()
}
commandBuffer.present(drawable)
commandBuffer.commit()
print("test")
PlaygroundPage.current.liveView = view
Crash report: https://gist.githubusercontent.com/tumdum/8aa53bc806619c0d21c93a55fae07937/raw/370b00c07b08fff8856f9fc678de9888faa8d06e/crash.log
I'm on macOS 15.1.1 (24B2091) + Xcode 16.2 (16C5032a)