Swift Playgrounds

RSS for tag

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

Swift Playgrounds Documentation

Posts under Swift Playgrounds tag

117 Posts
Sort by:
Post not yet marked as solved
3 Replies
593 Views
I would like to learn Xcode programming on MacOS. I was wondering if anyone knows of a step by step method. Where I can learn one command at a time but also all the nuances and syntax and instances for that command (function). I see a lot of tutorials for iOS programming but I would rather start and end with MacOS, but anything helps. I would like immersive instruction like what you would find in a cad classroom.
Posted
by
Post not yet marked as solved
0 Replies
824 Views
Why did I get an error in playground in debug window for this code? print("// MARK: - Start execable code here...") do { let store = CNContactStore() if try await store.requestAccess(for: .contacts) { // Do something with Contacts. let phoneNumber = CNPhoneNumber(stringValue: "903-276-1046") let predicateForContactsMatchingPhoneNumber = CNContact.predicateForContacts(matching: phoneNumber) let contactFetchRequest = CNContactFetchRequest(keysToFetch: thoroughKeysToCompare) contactFetchRequest.predicate = predicateForContactsMatchingPhoneNumber contactFetchRequest.unifyResults = true var contactOfMe: CNContact! = nil try! store.enumerateContacts(with: contactFetchRequest) { contact, stop in contactOfMe = contact stop.pointee = true } let contact = Contact(cnContact: contactOfMe) for property in contact.enumerated() { print("- \(property)") } } else { // Handle if Contacts access is denied. fatalError() } } catch { // Handle any error. print("error requesting access: \(error.localizedDescription)") } Debug window: // MARK: - Start execable code here... Playground execution failed: error: Execution was interrupted, reason: shared-library-event. The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation. * thread #1, queue = 'com.apple.main-thread' frame #0: 0x00007ff80002f931 libobjc.A.dylib`_mapStrHash(_NXMapTable*, void const*) + 73 frame #1: 0x00007ff80002fc7f libobjc.A.dylib`_NXMapMember(_NXMapTable*, void const*, void**) + 35 frame #2: 0x00007ff80003b7ae libobjc.A.dylib`getProtocol(char const*) + 41 frame #3: 0x00007ff8000428e6 libobjc.A.dylib`class_conformsToProtocol + 337 frame #4: 0x00007ff80004ab4e libobjc.A.dylib`-[NSObject conformsToProtocol:] + 47 frame #5: 0x0000000109c27951 UIKitCore`_UIFocusItemContainerIsScrollableContainer + 74 frame #6: 0x0000000109c28e38 UIKitCore`-[_UIFocusEnvironmentContainerTuple initWithOwningEnvironment:itemContainer:] + 194 frame #7: 0x0000000109c28fed UIKitCore`+[_UIFocusEnvironmentContainerTuple tupleWithOwningEnvironment:itemContainer:] + 70 frame #8: 0x0000000109c4f41e UIKitCore`_UIFocusRegionContainerFromEnvironmentAndContainer + 44 frame #9: 0x0000000109c27ed3 UIKitCore`_UIFocusItemContainerAddChildItemsInContextWithArguments + 1162 frame #10: 0x000000010a99c439 UIKitCore`-[UIView _searchForFocusRegionsInContext:] + 962 frame #11: 0x0000000109c6b37f UIKitCore`-[_UIFocusMapSnapshot addRegionsInContainer:] + 4583 frame #12: 0x0000000109c69740 UIKitCore`-[_UIFocusMapSnapshot _capture] + 456 frame #13: 0x0000000109c67fc5 UIKitCore`-[_UIFocusMapSnapshot _initWithSnapshotter:mapArea:searchArea:] + 628 frame #14: 0x0000000109c6cce2 UIKitCore`-[_UIFocusMapSnapshotter captureSnapshot] + 227 frame #15: 0x0000000109c5f450 UIKitCore`-[_UIFocusMap _inferredDefaultFocusItemInEnvironment:] + 147 frame #16: 0x0000000109c2b1cf UIKitCore`-[_UIFocusEnvironmentPreferenceEnumerationContext _inferPreferencesForEnvironment:] + 157 frame #17: 0x0000000109c2abbc UIKitCore`-[_UIFocusEnvironmentPreferenceEnumerationContext _resolvePreferredFocusEnvironments] + 118 frame #18: 0x0000000109c2ab12 UIKitCore`-[_UIFocusEnvironmentPreferenceEnumerationContext prefersNothingFocused] + 31 frame #19: 0x0000000109c2beeb UIKitCore`_enumeratePreferredFocusEnvironments + 198 frame #20: 0x0000000109c2c061 UIKitCore`_enumeratePreferredFocusEnvironments + 572 frame #21: 0x0000000109c2c061 UIKitCore`_enumeratePreferredFocusEnvironments + 572 frame #22: 0x0000000109c2c061 UIKitCore`_enumeratePreferredFocusEnvironments + 572 frame #23: 0x0000000109c2bd11 UIKitCore`-[_UIFocusEnvironmentPreferenceEnumerator enumeratePreferencesForEnvironment:usingBlock:] + 230 frame #24: 0x0000000109c2c747 UIKitCore`-[_UIDeepestPreferredEnvironmentSearch deepestPreferredFocusableItemForEnvironment:withRequest:] + 817 frame #25: 0x0000000109c95837 UIKitCore`-[UIFocusUpdateContext _updateDestinationItemIfNeeded] + 265 frame #26: 0x0000000109c95627 UIKitCore`-[UIFocusUpdateContext _destinationItemInfo] + 22 frame #27: 0x0000000109c95535 UIKitCore`-[UIFocusUpdateContext nextFocusedItem] + 24 frame #28: 0x0000000109c71ea6 UIKitCore`-[UIFocusSystem updateFocusIfNeeded] + 1347 frame #29: 0x0000000109c7608c UIKitCore`__43-[UIFocusSystem _updateFocusUpdateThrottle]_block_invoke + 34 frame #30: 0x000000010a94b971 UIKitCore`-[_UIAfterCACommitBlock run] + 57 frame #31: 0x000000010a94be71 UIKitCore`-[_UIAfterCACommitQueue flush] + 191 frame #32: 0x000000010a3926eb UIKitCore`_runAfterCACommitDeferredBlocks + 782 frame #33: 0x000000010a380fa2 UIKitCore`_cleanUpAfterCAFlushAndRunDeferredBlocks + 96 frame #34: 0x000000010a3b6be1 UIKitCore`_afterCACommitHandler + 58 frame #35: 0x00007ff8003b1c12 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23 frame #36: 0x00007ff8003ac57f CoreFoundation`__CFRunLoopDoObservers + 515 frame #37: 0x00007ff8003acaa2 CoreFoundation`__CFRunLoopRun + 1121 frame #38: 0x00007ff8003ac264 CoreFoundation`CFRunLoopRunSpecific + 560 frame #39: 0x00007ff8003ad234 CoreFoundation`CFRunLoopRun + 40 frame #40: 0x00007ff83755a4e3 libswift_Concurrency.dylib`swift_task_asyncMainDrainQueueImpl() + 35 frame #41: 0x00007ff83755a4b4 libswift_Concurrency.dylib`swift_task_asyncMainDrainQueue + 52 frame #42: 0x00000001015d409f $__lldb_expr32`main at <unknown>:0 frame #43: 0x0000000100e25560 EnumeratedContactsCNContact`linkResources + 256 frame #44: 0x00007ff8003b2986 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12 frame #45: 0x00007ff8003b2148 CoreFoundation`__CFRunLoopDoBlocks + 399 frame #46: 0x00007ff8003ace09 CoreFoundation`__CFRunLoopRun + 1992 frame #47: 0x00007ff8003ac264 CoreFoundation`CFRunLoopRunSpecific + 560 frame #48: 0x00007ff809b4024e GraphicsServices`GSEventRunModal + 139 frame #49: 0x000000010a3827bf UIKitCore`-[UIApplication _run] + 994 frame #50: 0x000000010a3875de UIKitCore`UIApplicationMain + 123 * frame #51: 0x0000000100e256c5 EnumeratedContactsCNContact`main + 357 frame #52: 0x0000000100fbb384 dyld_sim`start_sim + 10 frame #53: 0x000000010943341f dyld`start + 1903```
Posted
by
Post not yet marked as solved
1 Replies
858 Views
My while loop continues execution after reaching gemsCollected = 3 if I use OR logical operator (||) and stops execution if I use AND logical operator (&&). IMHO it should be the other way around, right? var gemsCollected = 0 var switchesToggled = 0 while gemsCollected < 3 || switchesToggled < 4 { moveForward() if gemsCollected < 3 && isOnGem { collectGem() gemsCollected = gemsCollected + 1 } else if switchesToggled < 4 && isOnClosedSwitch { toggleSwitch() switchesToggled = switchesToggled + 1 } else if isBlocked && !isBlockedRight { turnRight() } else if isBlocked && !isBlockedLeft { turnLeft() } }
Posted
by
Post marked as solved
2 Replies
466 Views
Hello community, This is my first post here. It's a super basic question. I'm starting to learn Swift and I'm using a Swift Playground from Xcode. I have tried to print a text like this: print("Hello, world") However the output is adding a "\n" symbol, resulting in: "Hello, world\n" Any thoughts? Thanks in advance, Rodrigo
Posted
by
Post not yet marked as solved
2 Replies
568 Views
I'm taking a response from an API and using below model, but I'm getting an error ObjectMapper fail to serialize response, what is wrong with the model ? import ObjectMapper // MARK: - RealTimeSummary class RealTimeSummary: Mappable { var realTimeSummaryReturn: ReturnRealTime = ReturnRealTime() var success: Bool = false required convenience init?(map: Map) { self.init() self.mapping(map: map) } func mapping(map: Map) { realTimeSummaryReturn <- map["Return"] success <- map["Success"] } } // MARK: - Return class ReturnRealTime: Mappable { var summary: Summary = Summary() var accounts: [AccountRealTime] = [] init(){} required convenience init?(map: Map) { self.init() self.mapping(map: map) } func mapping(map: Map) { summary <- map["Summary"] accounts <- map["Accounts"] } } // MARK: - Account class AccountRealTime: Mappable { var accountType: String = "" var accountNumber: String = "" var accountDescription: String = "" var accountProductCode: String = "" var availableBalance: Double = 0.0 var currentBalance: Int = 0 var holdAmount: Int = 0 init(){} required convenience init?(map: Map) { self.init() self.mapping(map: map) } func mapping(map: Map) { accountType <- map["AccountType"] accountNumber <- map["AccountNumber"] accountDescription <- map["AccountDescription"] accountProductCode <- map["AccountProductCode"] availableBalance <- map["AvailableBalance"] currentBalance <- map["CurrentBalance"] holdAmount <- map["HoldAmount"] } } // MARK: - Summary class Summary: Mappable { var availableBalanceTotal: Double = 0.0 var currentBalanceTotal: Int = 0 init(){} required convenience init?(map: Map) { self.init() self.mapping(map: map) } func mapping(map: Map) { availableBalanceTotal <- map["AvailableBalanceTotal"] currentBalanceTotal <- map["CurrentBalanceTotal"] } }
Posted
by
Post not yet marked as solved
0 Replies
472 Views
I'm encountering the same problem, the chart view stays blank! The code supposed to draw a PiChart with a customization in its style. The exercise is as follows: Pie Charts, Revisited The new API for pie charts exposes two new types: PieWedge and PieChartView. The PieWedge struct gives you several ways to create visual effects with pie charts. It has the following properties: proportion: The percentage of the pie occupied by the wedge, expressed as a Double. color: The color of the wedge. You can use any one of the following values. (Remember to use a period before the color name. If you don't, Swift will return a "use of unresolved identifier" error.) .black .blue .brown .cyan .darkGray .gray .green .lightGray .magenta .orange .purple .red .yellow scale: The radius of the wedge relative to the pie's natural radius, expressed as a Double. Less than 1.0 will make the wedge smaller than normal-sized wedges, and greater than 1.0 will make the wedge larger (typically the desired effect). offset: The distance a wedge lies from the center of the pie, relative to the size of the wedge. An offset of 0 keeps the wedge at the center of the pie. An offset of 1.0 moves the center point of the wedge to where its outer edge would be. The makePieChart() function creates an instance of a PieChartView named pieChartView. PieChartView has one property named wedges, which is an array of PieWedge instances. Assign an array of wedges to this property, or use the append() method of Array to add them one at a time. Keys makePieChart() also creates a key named keyView. It's an instance of ChartKeyView, which has a keyItems property. keyItems is an array of ChartKeyItem instances. ChartKeyItem has the following properties: color: The color swatch displayed in the key. You can use any of the following values. .black .blue .brown .cyan .darkGray .gray .green .lightGray .magenta .orange .purple .red .yellow name: The text to display expressed as a String. Create a pie chart using your own data. Play with different scale and offset properties to see how they affect the look of your chart. My Code: makePieChart() let myPiWedge1 = PieWedge(proportion: 0.1, color: .red, scale: 1.0, offset: 1.0) let myPiWedge2 = PieWedge(proportion: 0.4, color: .blue, scale: 1.0, offset: 1.0) let myPiWedge3 = PieWedge(proportion: 0.5, color: .yellow, scale: 1.0, offset: 1.0) var myPieChartViewArray = PieChartView().wedges myPieChartViewArray = [myPiWedge1, myPiWedge2, myPiWedge3] var myKeyView = keyView.keyItems let myChartKeyItem1 = ChartKeyItem(color: .red, name: "w1") let myChartKeyItem2 = ChartKeyItem(color: .blue, name: "w2") let myChartKeyItem3 = ChartKeyItem(color: .yellow, name: "w3") myKeyView = [myChartKeyItem1, myChartKeyItem2, myChartKeyItem3] I tried this as well, it shows the same issue: makePieChart () //Create an array of PieWedge instances var wedges: [PieWedge] = [] // Create individual PieWedge instances and add them to the wedges array let wedge1 = PieWedge(proportion: 0.3, color: .red, scale: 1.0, offset: 0) let wedge2 = PieWedge(proportion: 0.2, color: .blue, scale: 0.8, offset: 0.2) let wedge3 = PieWedge(proportion: 0.5, color: .green, scale: 1.2, offset: 0) wedges.append(wedge1) wedges.append(wedge2) wedges.append(wedge3) // Create an instance of PieChartView and assign the wedges array let pieChartView = PieChartView() pieChartView.wedges = wedges // Create an instance of ChartKeyView and configure its keyItems array let keyItem1 = ChartKeyItem(color: .red, name: "Red Wedge") let keyItem2 = ChartKeyItem(color: .blue, name: "Blue Wedge") let keyItem3 = ChartKeyItem(color: .green, name: "Green Wedge") let keyItems = [keyItem1, keyItem2, keyItem3] let keyView = ChartKeyView() keyView.keyItems = keyItems Any one can help? to me it sounds that the playground has some bug in it :) This exercise from the book "Explorations": Exploration --> Student --> 3-Organizing Data --> 2-Play with Complex Data --> I-Visualization Revisited
Posted
by
Post not yet marked as solved
8 Replies
935 Views
Can it be done? I can reliably crash Xcode by attempting the following in a playground: import UIKit import WeatherKit import CoreLocation let sanFrancisco = CLLocation(latitude: 37.7749, longitude: 122.4194) let weatherService = WeatherService() let weather = try await weatherService.weather(for: sanFrancisco) let temperature = weather.currentWeather.temperature print(temperature) Xcode 14.3.1 macOS 13.4.1
Posted
by
Post not yet marked as solved
1 Replies
722 Views
Is there a Form where I, a noobie, can ask really basic questions about this learning environment? As an example, I discovered the semi-colon in doing a task in the early part of "learn to Code" but I have not found any documentation for it. I am sure I will have other questions but right now I am just looking for a place to ask them. Thank you in advance.
Posted
by
Post not yet marked as solved
0 Replies
571 Views
When I import a package in Swift Playgrounds on my iPad, I receive the following error: This package interactions with libgit2, and it don’t have any release in the origin repository, so I find a existing fork which have release. Playgrounds version: 4.3.1(1727.53) Is it means that I install a software that supports unzip on iPad?
Posted
by
Post not yet marked as solved
0 Replies
438 Views
Hi, is there any possibility to localize my Swift Playgrounds APP? In the Build meta data it is always only English, and the "traditional" localization process doesn't work in Swift Playgrounds on iPad or in Xcode on Mac.
Posted
by
Post not yet marked as solved
2 Replies
531 Views
I have to admit that this is strange for me. Though I have been using playgrounds for years, but I only write small pieces of code to test simple ideas, and I never used another source file. Today I want to add a new struct in Sources folder. To my surprise, I am not able to reference the struct in the main playground file. Sources/testlets.swift: struct Dummy { var name: String } MyPlayground: var box = Dummy(name: "abc") // error: /.../MyPlayground.playground:22:11 Cannot find 'Dummy' in scope
Posted
by
Post not yet marked as solved
0 Replies
500 Views
I've decided I want my app, which has been shipped to the App Store, to support CloudKit, but it's a .swiftpm app (so I could work on it on the go on an iPad and Swift Playgrounds). I've taken a half-hearted stab at it (there's more pressing stuff to work on and this is a nice to have for the moment), but is there a way to set up a new workspace in Xcode where I have two targets: a .swiftpm version of the app and a .xcodeproj app so I can enable CloudKit for my app and also ship it to the App Store with the same identifier?
Posted
by
Post not yet marked as solved
0 Replies
504 Views
I am typing string text on textDocumentProxy in a custom keyboard app. The input text includes newlines and punctuation letters, but when I try to edit the textDocumentProxy field, the textDocumentProxy.documentContextBeforeInput in case a newline \n is included, it does not return full content before input. I placed the cursor on after the good morning word center, I got only good string text. The remaining "hi folks", words do not return. Here are some examples I have tried. var inputText = "Hi folks, Good morning to everyone " var txtBeforeCursor = textDocumentProxy.documentContextBeforeInput ?? "" print("Before Cursor text : ",txtBeforeCursor) Output is: Before Cursor text : Good
Posted
by
Post not yet marked as solved
2 Replies
391 Views
Im new to Xcode getting this error in this playground, can someone help me here... This was In a playground btw Thanks, struct Digit { var number : Int init(_ n: Int){ self.number = n } mutating func changeNumberTo(_ n:Int) { self.number = n } func otherFunction(_ f: ()-&gt;()) { } mutating func callAnotherFunction() { otherFunction { self.changeNumberTo(345) // * } } } var d = Digit(123) // Digit is a struct print(d.number) //123 var d2 = d //Assignment! d2.number = 42 print(d.number) enum Node { case none(Int) indirect case left(Int, Node) indirect case right(Int, Node) indirect case both(Int, Node, Node) }
Posted
by
Post not yet marked as solved
1 Replies
522 Views
Hi, dear community, I recently updated my old Macbook pro(model 2016) to Monterey(which is the latest macOS that support 2016 model), but the Swift Playgrounds on AppStore requires macOS 13. Is there any way I can get the app, just like Xcode? Xcode provides an alternative way to download the xip file of an older version, but playgrounds does. Many thanks in advance, any help will be appreciated!
Posted
by
Post not yet marked as solved
2 Replies
588 Views
I have the simplest Playground to display image. I have images inside Resources. Somewhat it does not work and I am really confused. I am using macOS XCode. I think on iPad Swift Playground this might work. import SwiftUI import PlaygroundSupport struct ContentView: View { var body: some View { Image("image1") .resizable() .frame(width: 512, height: 512) } } let hostingController = UIHostingController(rootView: ContentView()) PlaygroundPage.current.liveView = hostingController
Posted
by
Post not yet marked as solved
2 Replies
717 Views
Since Swift Playgrounds was able to submit Apps to the AppStore ,Apple stated that it can be used to develop apps without having to use Xcode. But if you do so you are lost: The Testflight beta versions of Swift Playgrounds with API support for iOS 17 and macOS 14 have expired one week before the new systems become/became available and there is still no final version! If you used Playgrounds to develop an iOS 17 ready version of your app you can't do anything now and that at a time where the users get their hands on the new OS. That is really bad.
Posted
by