I've written the code exactly the way the tutorial explained. Word for word. The tutorial states to write @State var selected = "Bowling" but that doesn't work. I asked for help before but no one replied. So I thought I would post again with the code.
Swift Playgrounds
RSS for tagLearn and explore coding in Swift through interactive learning experiences on the Swift Playgrounds app for iPadOS and macOS.
Posts under Swift Playgrounds tag
94 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Thanks for zero replies. I can't believe that 28 to 51 people looked at my post and no one responded back. Anyway, I figured it out on my own after taking a break. I was just asking in so many words, where do I put the bold highlighted code.
WHY NOT TRY app completed……….
//
// ContentView.swift
// WhyNotTry
//
// Created by Geraldine Jones on 1/26/24.
//
import SwiftUI
struct ContentView: View {
var activities = ["Archery", "Baseball", "Basketball", "Bowling", "Boxing", "Cricket", "Curling", "Fencing", "Golf", "Hiking", "Lacrosse", "Rugby", "Squash"]
var colors: [Color] = [.blue, .cyan, .gray, .green, .indigo, .mint, .orange, .pink, .purple, .red]
******** @State private var selected = "Baseball"********
@State private var id = 1
var body: some View {
VStack {
Text("Why not try...")
.font(.largeTitle.bold())
VStack {
Circle()
.fill(colors.randomElement() ?? .blue)
.padding()
.overlay(
Image(systemName: "figure.\(selected.lowercased())")
.font(.system(size: 144))
.foregroundColor(.white)
******** .transition(.slide)********
******** .id(id)********
)
Text("\(selected)!")
.font(.title)
}
Spacer()
Button("Try again") {
****** withAnimation(.easeInOut(duration: 1))****** {
selected = activities.randomElement()
?? "Archery"
********id += 1********
}
}
.buttonStyle(.borderedProminent)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
https://www.swift.org/getting-started/swiftui/
Is there a better tutorial than this one. Can't seem to find a live youtube video that teaches it. I went to git hub and downloaded the source code but all it shows is a big round blue circle. I can't seem to get pass the below code without it giving me an error. I need to see this tutorial live. Any suggestions?
struct ContentView: View {
var activities = ["Archery", "Baseball", "Basketball", "Bowling", "Boxing", "Cricket", "Curling", "Fencing", "Golf", "Hiking", "Lacrosse", "Rugby", "Squash"]
var selected = "Archery"
var body: some View {
// ...
}
}
I am developing my app for the Swift Student Challenge 2024. I have made significant progress on it and have been building it on a M1 Mac, where it works perfectly. However, when testing it on some iPads (specifically, the iPad Pro 2018 and iPad Air 5 M1), it did not perform well on these devices.
I am wondering if I can specify whether the app should be reviewed on a Mac (M1 or later) or if it will be reviewed on an iPad.
Hi! I'm preparing to apply for the Swift Student Challenge and had a question, how can I find info.plist in Xcode 15.2 playground I will do a game AR game and I need info.plist to access to camera so how can I find info.plist ?
I am using Swift Playground to teach "coding" to my nephew. One of the strict requirements I am trying to explain him is: when you are required to solve a problem, you need to use only the instructions/harward/etc you have available.
In the first episode of "Get started with code" -> "Commands" -> "Issuing commands", you are presented with two commands moveForward() and collectGem().
In the second episode "Toggle a Switch" you are introduced to a new command "toggleSwitch()".
Up to this point, the learner was introduced to three commands: moveForward(), collectGem(), toggleSwitch().
However, in order to solve the puzzle in the second episode, you need also to use another command: turnLeft(), that has not been referenced.
It is clear that looking for unknown commands is part of learning to code, but this occurs too early in the playground. Please consider also that some non-English young learners have no idea on how to write "turn left", so they cannot even type the first letters and hope in the auto-completion of the commands.
This has not been well thought by the designers of the playground.
Hi! I'm preparing to apply for the Swift Student Challenge and had a question.
In the terms and conditions, it says
"Your app playground must be built with and run on Swift Playgrounds 4.4 or later (requires iPadOS 16 or macOS 13.5) or Xcode 15 on macOS 13.5 or later. You may incorporate the use of Apple Pencil."
Does this mean that my app must run on iPadOS 16 or macOS 13.5, or can it run on iPadOS 17 or macOS 14 or later as long as it runs on Playgrounds 4.4?
In other words, what should I set my Deployment Target to?
Thanks for your help in advance 😜
Hello everyone,
Is there a way to set the minimum deployment target in Xcode Playground?
Hello,
I'm developing an app for Mac, Xcode 15.1, with Swift 5.
I need to create a visual matrix, whose elements will be filled randomly, according to the choices the user makes.
The matrix must have 10 columns and 40 rows.
Does anyone know a component, or how to fill it dynamically and randomly?
Thanks.
Hey folks!
I remember some weeks/months ago to get some lessons with updated Swift 5.9, I'm just not sure if this happened while I was using Swift Playgrounds beta from TestFlight.
Anyways, I went back to study using Swift Playgrounds and all the lessons are using Swift 5.8 here.
I don't know what happened or how can I have the lessons updated again.
Anyone else noticed this issue? Any tip on how to solve it?
I am trying to implement a ML model with Core ML in a playground for a Student Challenge project, but I can not get it to work. I have already tried everything I found online but nothing seems to work (the tutorials where posted long time ago). Anyone knows how to do this with Xcode 15 and the most recent updates?
Hi!
I'm participating in the Swift Student Developer competition this year, which requires developers to present a Swift Playground to Apple. I'm used to making normal Xcode projects, and am having trouble finding a Swift Playgrounds version of the Copy Bundle Resources build phase (I don't think it is possible to edit build phases in a Swift Playground).
I created a '.usdz' file from a 3D model I designed using Reality Converter and added it to the root of my Swift Playground project. I access the file programmatically from the App Bundle like so (fileName is a non-nullable String):
guard let path = Bundle.main.path(forResource: fileName, ofType: "usdz") else { fatalError("Couldn't find the USDZ file.") }
At runtime, this throws the Couldn't find the USDZ file error, as the file isn't being copied to the App Bundle.
In a normal Xcode project, according to this StackOverflow question, I can get xcodebuild to copy my file over by specifying it in the Copy Bundle Resources build phase, however, in a Swift Playground (required by Apple), I am restricted from modifying Xcode's buildphases (the option is not present when clicking on the default target - the only options are General, Signing & Capabilites and Package Dependencies).
How can I ensure that resources are copied over to the App Bundle at buildtime in a Swift Playground?
If this is not possible, are there any other options besides using the Bundle.main.path API for accessing the USDZ file (to load a QuickLook preview) at runtime?
I am currently working on my project for the Swift Student Challenge 2024. I am trying to implement a feature (.defaultScrollAnchor on a ScrollView in this instance). However, when trying to build/run the app in Xcode it says that .defaultScrollAnchor is only compatible with iOS 17. If I try to use .scrollPosition(initialAnchor: ), it also doesn't work (likely because it has been depreciated). I printed the system version as suggested in another post, and it showed the simulator was running iOS 17.2. Why can't the app build/run with this feature if the simulator is running iOS 17.2?
MacBook Pro 14" 2021 M1 Pro
Xcode Version 15.1
macOS Sonoma 14.0
Using Xcode 15.0.1
The playground, for the code below, has been in "Launching ok" for over two minutes. Anything that I should look into? A little mind boggling actually.
import UIKit
var msg = "Hello World"
print ("\(msg)")
I have same code in Xcode and Playground. But Xcode is not previewing the View the right way. Here is a screenshot of Xcode:
and here is the screen of Playground:
when i run the code (command + R) it's working fine and i get the true preview in the app (just like what i get in Playground).
Am I doing something wrong or is it a bug?
The code below is a json parser example. I used the quick type website to build my structs for reading in the json. All that code works but I am having an issue with looping thru the data read. I am trying to read this is a view, so I can not use a for statement. I am having issues learning how to use the ForEach Statement to loop on the contacts in this json data and print the firstName, lastName for each contact.
This is the Code
let data1JSON = """
[
{
"data": {
"viewer": {
"__typename": "Member",
"id": 123,
"firstName": "d",
"lastName": "a",
"emailAddress": "w"
},
"league": {
"id": 1111,
"name": "a",
"slug": "b",
"isMine": true,
"logo": "g",
"homePageUrl": "bA",
"facebookUrl": "www.facebook.com/B",
"phone": "1",
"contacts": [
{
"id": 12,
"firstName": "",
"lastName": "d",
"phone": null,
"__typename": "Contact"
},
{
"id": 10,
"firstName": "",
"lastName": "c",
"phone": null,
"__typename": "Contact"
}
],
"__typename": "League"
}
}
}
]
"""
// MARK: - ApaResultElement
struct ApaResultElement: Codable {
let data: DataClass
}
// MARK: - DataClass
struct DataClass: Codable {
let viewer: Viewer
let league: League
}
// MARK: - League
struct League: Codable {
let id: Int
let name, slug: String
let isMine: Bool
let logo: String
let homePageURL, facebookURL, phone: String
let contacts: [Viewer]
let typename: String
enum CodingKeys: String, CodingKey {
case id, name, slug, isMine, logo
case homePageURL = "homePageUrl"
case facebookURL = "facebookUrl"
case phone, contacts
case typename = "__typename"
}
}
// MARK: - Viewer
struct Viewer: Codable {
let id: Int
let firstName, lastName: String
let phone: JSONNull?
let typename: String
let emailAddress: String?
enum CodingKeys: String, CodingKey {
case id, firstName, lastName, phone
case typename = "__typename"
case emailAddress
}
}
typealias ApaResult = [ApaResultElement]
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
public var hashValue: Int {
return 0
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
let decoder = JSONDecoder()
let leagueView = data1JSON.data(using: .utf8)!
do {
try decoder.decode([ApaResultElement].self, from: leagueView)
print("success")
}
catch {
print("Error found => \(error)")
}
let d1 = try decoder.decode([ApaResultElement].self, from: leagueView)
// This is where I need help to loop the json to extract all the data
// I see that I need to loop on each array stuct to do that.
I have looked for a good tutorial on ForEach, but none of the sites I found help me look on this JSON Data.
I am new to swift and the autocomplete feature, so any tips using Apple Developer Documentation or the Code Complete would also be appreciated.
Thanks
Hello, someone told me that I can get a programming certificate when I complete (Learn to Code 1) from the Swift Playground application, is this true?? And if it is true, how do I get it?
Hi, Everyone
I set up a class for sharing photos to facebook. The codes of the class are as following. But when I call the function "shareToFacebook", there is no dialog to show. What's the issue in these codes? I am using iOS 17.0, Xcode The guide from Facebook hasn't updated.
import SwiftUI
import FBSDKShareKit
import FacebookShare
@Observable
class ShareFacebook {
var content = SharePhotoContent()
var images : [UIImage] = []
var photos : [SharePhoto] = []
func shareToFacebook() {
for image in images {
let photo = SharePhoto(
image: image,
isUserGenerated: true
)
photos.append(photo)
}
content.photos = photos
let dialog = ShareDialog(
viewController: UIApplication.shared.currentUIWindow()?.rootViewController,
content: content,
delegate: nil )
dialog.show()
}
}
//button for sharing
//Sharing to Facebook
Button {
for image in photos {
let image = UIImage(data: image.imageData)
sharedPhotos.append(image ?? userViewModel.render(image: Image("photoForNil"))! )
}
shareToFacebook.images = sharedPhotos
shareToFacebook.shareToFacebook()
}label: {
Image("share")
.resizable()
.frame(width:18, height: 18)
.padding(.trailing,30)
}
I am trying to generate a simple playground to display Table structure with several TableColumns. Basically, generated a new blank playground; add import statements for SwiftUI and PlayGround support; add structure for content view and a statement for invoking that view as:
`PlaygroundPage.current.setLiveView(ContentView())
In general, all of the view components work as expected EXCEPT for the table structure which does not display anything. Its basic structure is:
Table(rows, selection: $selRow) {
TableColumn("ID") {Text(String($0.id))}
TableColumn("Name", value: \.nt)
}
where "rows" is an array of the structure TRow:
struct TRow : Identifiable {
var id:Int
var num:Int
var nt:String
}
Is there some special trick to allowing a SwiftUI Table to be displayed in Playground?
Hi,
I wanted to learn basics on developing in iOS and started with Swift Explorations. I have installed Xcode 15.0.1 and running it on Ventura 13.5.1. When I execute the Playgroung Basics.playground file, I get an error message saying "Failed to attach to stub for playground execution".
Any clue as to why that might be? I am able to create my own playground and execute it properly. I searched around but could not find anything on the topic (other than disablig Rosetta which is not an option as far I can tell in my case; don't see that checkbox under Get Info).
Any pointer would be welcome.
Cheers,
Piloo