Hello everyone. I was a building a test app when I encountered this error:
I'm new to indices and am a bit confused by them. Can someone please explain the error to me and show me a possible solution to it? Many thanks!
Here is my code:
import SwiftUI
struct GameView: View {
@StateObject var viewModel = GameViewModel()
var body: some View {
ZStack {
GameColor.main.ignoresSafeArea()
VStack {
Text(viewModel.progressText)
.padding()
Spacer()
Text(viewModel.questionText)
.font(.title)
.multilineTextAlignment(.center)
.padding()
Spacer()
Spacer()
HStack {
ForEach(0..<viewModel.answerIndices.count, id: \.self) { index in
AnswerButton(text: viewModel.answerIndices[index]) {
// ForEach(viewModel.answerIndices) { index in
// AnswerButton(text: viewModel.answerText(for: index)) {
viewModel.makeSelectionForCurrentQuestion(at: index)
}
.background(viewModel.colorForButton(at: index))
.disabled(viewModel.selectionWasMade)
}
}
if viewModel.selectionWasMade {
Button(action: viewModel.advanceGameState,
label: {
BottomText(str: "Next")
})
}
}.padding(.bottom)
}
.navigationBarHidden(true)
.background(resultsNavigationLink)
}
private var resultsNavigationLink: some View {
NavigationLink(
destination: ResultsView(viewModel: ResultsViewModel(selectionCount: viewModel.selectionCount, gameStartTime: viewModel.gameStartTime, gameEndTime: Date())),
isActive: .constant(viewModel.gameIsOver),
label: { EmptyView() })
}
}
struct AnswerButton: View {
let text: String
let onClick: () -> Void
var body: some View {
Button(action: {
onClick()
}) {
Text(text)
}
.padding()
.border(Color.blue, width: 4)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
GameView()
}
}
}
(Above is the view; this is the model:
import SwiftUI
class GameViewModel: ObservableObject {
@Published var game = Game()
var questionText: String {
game.currentQuestion.questionText
}
var answerIndices: Range<Int> {
game.currentQuestion.possibleAnswers.indices
}
var correctAnswerIndex: Int {
game.currentQuestion.correctAnswerIndex
}
var progressText: String {
"Question \(game.currentQuestionIndex + 1) / \(game.questionCount)"
}
var selectionWasMade: Bool {
game.selections[game.currentQuestion] != nil
}
var selectionCount: (Int, Int) {
game.selectionCount
}
var gameIsOver: Bool {
game.gameIsOver
}
var gameStartTime: Date {
game.startTime
}
func answerText(for index: Int) -> String {
game.currentQuestion.possibleAnswers[index]
}
func advanceGameState() {
game.advanceGameState()
}
func makeSelectionForCurrentQuestion(at index: Int) {
game.makeSelection(at: index)
}
func colorForButton(at buttonIndex: Int) -> Color {
guard let selectedIndex = game.selections[game.currentQuestion], selectedIndex == buttonIndex else { return .clear }
if selectedIndex == correctAnswerIndex {
return .green
} else {
return .red
}
}
}
Thanks for the help in advance!
Swift
RSS for tagSwift is a powerful and intuitive programming language for Apple platforms and beyond.
Posts under Swift tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I have a problem with reload data in table view. My app structure has two container views, where the first container view is collection view controller and the second container view is table view controller. In collection view, I select the cell and in table view I want to show information. I need to reload all the data in table view because I can select any cell in the collection view.
In selectedDay I get information about the cell I selected in didSet I make a request to Firebase (fetchDataFromFirebase) and get information for the selected day. After that, I append data in workoutList array and in didSet I need to reload all my table view.
My code in TableViewController
class ScheduleTableViewController: UITableViewController {
var selectedDay: Day? {
didSet {
workoutList.removeAll()
fetchDataFromFirebase(day: selectedDay?.day ?? "",
month: selectedDay?.month ?? "",
year: selectedDay?.year ?? "")
}
}
weak var delegate: EmptyDataInSelectedDayProtocol?
private var workoutList = [NewWorkout]() {
didSet {
print(workoutList)
print(workoutList.count)
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return workoutList.count
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ScheduleTableViewCell
cell.configure(in: workoutList[indexPath.row])
return cell
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView,
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let reSchedule = UIContextualAction(style: .normal, title: "Change workout day") { [unowned self] action, view, completionHandler in
workoutList.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
completionHandler(true)
}
reSchedule.image = UIImage(systemName: "arrow.up.arrow.down")
reSchedule.backgroundColor = .primary.withAlphaComponent(0.8)
return UISwipeActionsConfiguration(actions: [reSchedule])
}
private func fetchDataFromFirebase(day: String, month: String, year: String) {
FirebaseHelper.shared.getRefenceFirebase()
.child("\(FirebaseHelper.shared.getUserID())").observe(.value) { [self] snapshot in
DispatchQueue.main.async { [self] in
guard let value = snapshot.value as? [String:Any] else {return}
for info in value {
let data = value["\(info.key)"] as? NSDictionary
guard let userName = data?["userName"] as? String else {return}
guard let trainingStartDate = data?["trainingStartDate"] as? String else {return}
guard let trainingTime = data?["trainingTime"] as? String else {return}
guard let workoutDuration = data?["workoutDuration"] as? String else {return}
guard let selectedColor = data?["selectedColor"] as? [String:Any] else {return}
guard let workoutDates = data?["workoutDates"] as? [String] else {return}
guard let weekDays = data?["weekDays"] as? [String:Any] else {return}
for item in workoutDates {
if "\(day).\(month).\(year)" == item {
delegate?.isEmptyData(in: false)
let workout: [NewWorkout] = [NewWorkout(userName: userName,
weekDays: weekDays,
trainingStartDate: trainingStartDate,
workoutDuration: workoutDuration,
wortoutTime: trainingTime,
userColor: [UserColor(red: selectedColor["red"] as? Double ?? 0.0,
green: selectedColor["green"] as? Double ?? 0.0,
blue: selectedColor["blue"] as? Double ?? 0.0)],
workoutDates: workoutDates)]
workoutList.append(contentsOf: workout)
}
}
}
}
}
}
}
Dear community,
I'm reading "Develop in Swift Fundamentals", and on page 89 it asks us to open a file from the downloaded file (page 9 - Download Student Materials link).
I was running the last part of the exercise of page 89 and it seems I got stuck when trying to remove the last compile warning message:
"1. Condition always evaluates to false"
"Will never be executed"
Please take a look at the screenshot, where you can see the whole code and context.
I have tried to add a few breakpoints (rows 10 to 12) in order to see if they would get ignored but it looks like it's still there.
Any idea how to remove / get rid of this compile warning message?
Thanks,
Rodrigo
I am sorry for my poor English.
I know that a callback of timer is not called in background mode. I know that I should add capabilities, permissions and keys into the Info file for doing something in background mode.
But I do not need any complicated task in background mode, just need to terminate my app automatically after 30 minutes in background mode.
Is there a simple way for that purpose?
I had to update a simple piece of code, so it could be delayed by a few ms in some cases. This is how I tried to achieve that, by using a Task:
class SomeClass {
private var availableStuff : Set<Stuff> = []
func updateStuff(lookingFor prop: SomeProp,
updatedThing: String,
waiting: Duration = .zero)
{
Task {
if waiting != .zero {
try await Task.sleep(for: waiting)
}
if var stuff = availableStuff.first(where: { $0.prop == prop }) {
stuff.thing = updatedThing
// print(availableStuff)
self.availableStuff.remove(stuff)
self.availableStuff.insert(stuff) // BAD ACCESS here
}
}
}
}
It did work before implementing the delay, but now it would crash at the insert statement (sometimes at remove). Naively, I put a print statement beforehand and to my surprise, this kept the crash from occurring at all!
I switched on Address Sanitizer, now it doesn't crash, even w/o the print statement.
Am I using the Task wrong, somehow?
How can I further diagnose this, so it doesn't happen later in production?
Or should I just leave the print in and hope for the best?
Thanks!
I am trying to get simple crash detection working. Ten years ago was that no problem with Obj-C thankss to the UncaughtExceptionHandler. But Swift needs more work and I am not sure I am on the right path after I the TheEskimos posts.
I tried the following implementation, based on other approaches and comments. To my surprise it seems not to get called.
Any idea what I am missing or doing wrong?
import Foundation
class CrashDetection: NSObject {
private static let observedSignals = [SIGABRT, SIGILL, SIGSEGV, SIGFPE, SIGBUS, SIGPIPE, SIGTRAP]
private static var previousSignalHandlers: [Int32:(@convention(c) (Int32) -> Void)] = [:]
@objc class func start() {
NSSetUncaughtExceptionHandler(CrashDetection.recieveException)
observedSignals.forEach { signalType in
let oldHandler = signal(signalType, CrashDetection.recieveSignal)
CrashDetection.previousSignalHandlers[signalType] = oldHandler
}
}
private static let recieveException: @convention(c) (NSException) -> Swift.Void = {
(recieveException) -> Void in
UserDefaults.standard.setValue(true, forKey: "crashDidOccur")
}
private static let recieveSignal: @convention(c) (Int32) -> Void = {
(recievedSignal) -> Void in
UserDefaults.standard.setValue(true, forKey: "crashDidOccur")
NSSetUncaughtExceptionHandler(nil)
observedSignals.forEach { signalType in
signal(signalType, previousSignalHandlers[signalType])
}
}
}
Hi,
Is there any reasonable way to use MusicKit on the Vision Pro simulator. I have been unable to get anything working and I was wondering if the situation is the same as iOS etc where you need a physical device to test the app.
Im having an issue with my View. When ever i want to put it inside of a ScrollView there is extra padding that appears. I tested to find the cause of it but to no luck. Here is the code for it :
NavigationView{
NavigationLink(destination: HiringAdPage(favorite: true)) {
HiringAds()
}
.buttonStyle(PlainButtonStyle())
}
the ScrollPart of it :
ScrollView{
VStack(spacing: 0) {
ForEach(0..<5) {index in
HiringAdsView()
}
}
}
Someone please help been trying for a while now..
I've customized the US locale with a metric measurement system, but when selectin natural unit style, I still got an imperial formatted distance string. (feet, miles etc)
this also reproduces in the playground
The expected behavior here is for the formatter to use the measurement system in the Locale object
I need to restrict to UITextField text cursor should only focus on end of text every time. Ex- if user entered OTP in textField and again he want to replace digit from text field when he tap to UITextField then cursor should focus on end of text only not beginning of text. I added below code
func textFieldDidBeginEditing(_ textField: UITextField){
DispatchQueue.main.async{
let position = textField.endOfDocument
textField.selectedTextRange = textField.textRange(from: position, to: position)
}
}
It is working On first time textfield selection. After once cursor focussed in UITextField that time it is moving to Start position if user tap on start position.
We are using the Speech framework to enable users to interact with our app via voice commands. When a user says "start test" we send
DispatchQueue.main.async {
self.startButton.sendActions(for: .touchUpInside)
}
This works beautifully, except that the screen goes into auto lockout in the middle of a test. Apparently, using sendActions does not actually send a touch event to the OS.
My question is how can I tell the OS that a touch event happened programmatically?
Thank you
I am attempting to create a C++ file called Fish and to display the fish's num in my SwiftUI app. However, I am encountering the errors "expected ';' after top level declarator" and "unknown type name 'class'; did you mean 'Class'?". It appears that Xcode thinks that the file is a C file. How should I address these errors?
I am building an app that uses the RoomPlan API, but I am hoping to change the UI, is it possible to, for instance, change the color of the lines that are displayed? Also, there only appears to be a way to turn off the live model, not translate it around the screen. Is it possible to do either of these things in IOS 17's RoomPlan?
Working for a telephony provider, I had to implement something that checks if the device supports eSIM. And when checking on a device like iPhone 13 Pro it returns false. Why is that the case? Can someone help?
var supportsESIM: Bool {
cellularPlanProvisioning.supportsCellularPlan()
}
private let cellularPlanProvisioning = CTCellularPlanProvisioning()
The MetricKit implementation is pretty straight forward. I am testing it now for a couple of days, but I never saw any report passed to my test apps. (implemented it in an empty app that just crashes every now and then and in a product of ours)
The function 'didReceive' is never called and each time I am asking 'MXMetricManager.shared.pastDiagnosticPayloads' I get an empty collection.
So that is the secret here? Is MetricKit not working for development builds? Or are there other factors/requirements not meet?
import Foundation
import MetricKit
class CrashDetection: NSObject, MXMetricManagerSubscriber {
@objc static let shared = CrashDetection()
@objc private override init() { }
internal static var crashDidOccur: Bool {
get { UserDefaults.standard.bool(forKey: crashDidOccurKey) ?? false }
set { UserDefaults.standard.set(newValue, forKey: crashDidOccurKey) }
}
@objc func start() {
MXMetricManager.shared.add(self)
}
@objc func stop() {
MXMetricManager.shared.remove(self)
}
func didReceive(_ payloads: [MXDiagnosticPayload]) {
let crashDiagnostics = payloads.compactMap({ $0.crashDiagnostics })
CrashDetection.crashDidOccur = crashDiagnostics.isEmpty == false
}
}
Rectangle()
.fill(
RadialGradient.radialGradient(
colors: [.blue, .yellow],
center: UnitPoint(x:0.5, y:0.5),
startRadius: 0,
endRadius: 50)
)
.frame(width: 100, height: 100)
In the above code I have a Rectangle with simple radial gradient as follow:
I wanna apply an arbitrary transformation matrix to the gradient so I can achieve following effects:
I tried following.. but it applying the transformation matrix to frame instead of shader/gradient
Rectangle()
.overlay(
RadialGradient.radialGradient(
colors: [.blue, .yellow],
center: UnitPoint(x:0.5, y:0.5),
startRadius: 0,
endRadius: 50)
.transformEffect(
CGAffineTransform(
-0.5000000596046448, 0.4999999403953552,
-0.972577691078186, -0.9725777506828308,
0.5000000596046448, 1.4725778102874756)
.translatedBy(x: -50, y: -100)
)
)
.frame(width: 100, height: 100)
it result in transformation of frame intreat of shader/gradient:
Thanks in advance 🙌🏻
I am running into this error when trying to archive the file to release the app to TestFlight. How can I fix this error?
I know how to match unknown number of fields with using 'range' and '.regularExpression' option as shown below, but how do i do it with the new RegexBuilder or multi-line literal?
func matches(for regex: String, in text: String) -> [String] {
var result = [String]()
var startIndex = text.startIndex
let endIndex = text.endIndex
while let range = text.range(of: regex,
options: .regularExpression,
range: startIndex ..< endIndex)
{
result.append(String(text[range]))
startIndex = range.upperBound
}
return result
}
I have a CRUD app built with flutter. Now I want to use Swift to create a widget to show the data at home screen.
I use json to store the data. In the following code if I replace jsonURL with mock json string, everything works well. So I think the problem comes from accessing the local file.
let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.app.identifier")
let jsonURL = sharedContainerURL?.appendingPathComponent("things.json")
And this is how I create the json file with Dart.
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/$storageName.json');
}
In a nutshell the problem is that the widget cannot access the json file I created in the app storage. Everything works well except the widget.
I have an angular project that I want to deploy using swifter in swiftUI. I have tried the below code.
import Foundation
import Swifter
class WebServer {
let server = HttpServer()
let path: String
init(path: String) {
self.path = path
}
func startServer() {
if let webAppPath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "fileDir") {
// Serve the Flutter web build files
server["/"] = shareFilesFromDirectory(webAppPath)
server["/hello"] = { .ok(.htmlBody("You asked for \($0)")) }
do {
try server.start(8081)
print("Web server started on port 8081")
} catch {
print("Failed to start the web server: \(error)")
}
} else {
print("Web app path not found.")
}
}
func stopServer() {
server.stop()
print("Web server stopped")
}
}
When trying this, web server is starting successfully, but when running baseUrl on localhost 8081, it gives 404. On "/hello", it does work correctly.
I am sure all the files are there in the directory given in fileDir.
Also I have tried running it using npm http-server, and it running correctly with it.
Can someone point out the issue here? Or point me to any github repo which is achieving same with maybe a different package