/r/swift
Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.
Dedicated to the Swift programming language released by Apple. More info in the Swift Wiki.
Please, check the FAQs before submitting.
General Swift Discussion
irc.freenode.net #swift-lang
Cocoa/Cocoa Touch Discussion
irc.freenode.net #cocoa-init
Keywords: swift, swiftlang, ios, os x, apps, apple, mac, iphone, ipad
/r/swift
I have requested the entitlement for more than 3 weeks and I still didn't get any response , how long would it take ?
I have requested the entitlement for more than 3 weeks and I still didn't get any response , how long would it take ?
I have a few MacOS SwiftUI apps that I would like to release on my own website without a paid developer license, and I’m not sure if I can, or how. I have never found a solid answer to this question, so I am asking here. Has anyone ever done this?
Suppose I have an array of strings. Then I want to use a custom struct called Letter with parameters of type LetterState (custom type made with an enum) and String
Letter(letterState: LetterState, letter: String)
What this struct does is display a letter in a box. The letterstate is something I use to change the color of the box. Now I have an array of 6 strings. By default all the strings at just
""
However, when the user inputs a word, the word replaces one of the empty strings in this array. What I want to do is use each character of that word as the input for the letter parameter so that each character would be in its own box (with a for loop). How would I do this?
I hope I described it well enough
I mean, from my point of view, Apple is not working super hard on SwiftUI, Xcode is beautiful, but a nightmare to really work with and it looks like nothing is made to fix it etc..
Like most big companies (especially Tech), they are super secretive, but I'm pretty sure that they have a good view of what Apple will be and will create for the next decade.
Yet, even you, the creator and contributor to the Apple ecosystem, don't seem to know much about what's going to happen next.
In web dev, there are so many softwares, new languages/frameworks appear all the time. If one fails, a new one will pop up to take the lead on a particular task.
What if "tomorrow" they create a full Swift no-code software powered by a super Apple AI?
Of course, you could always learn a new language. But doesn't it bother you to only depend on Tim's decisions?
Timecode 01:03:08 is devoted to differentiable Swift
When working with SwiftData is it better to use the Query property wrapper or creating a view model that has CRUD methods? I'm finding it difficult to write unit testing for my SwiftData model and Paul Hudson seems to suggest using a viewmodel instead to facilitate better testing. I imagine there are quite a few opinions on this so I'm curious to hear what others think.
Hey guys
I have created 2 model sources in Apple's create ML software, which are hand action classifiers for sign language words. How can I implement BOTH of these to run simultaneously into a swift application, through a live camera feed. So basically, with a live webcam, when the user performs a hand action/ASL sign (based on the classes in the trained models), it is predicted in real time through the web-cam, using the already trained core ML model trained in create ML. Note that I want both the models to perform simultaneously, as they both have their own separate classes (I split part of the dataset into two models for better performance, I am currently testing this with just 2, but plan to make it 4-5 model sources later on).
Couldn't find any apple developer documentation on this and don't have too much experience with swift, so I need some help. Thanks so much!
I have an application that's in development and using Core Data only. I do not need every user on the planet to be able to run the app, so I would be okay with the current number of users with iOS 17, being able to run it.
Do you think it would be a good idea to have the application changed to use Swift Data now, rather than later. Is it sufficiently bug free? Are there many advantages to switching over?
Hello just wanna if you were afraid when you started to invest only on one platform (apple) and be tied to it ?
I feel like Mowgli finding himself in the Metropolis. Although, partly, it's more like the truth than an analogy. I live in a third-world country, and the level of education here still leaves much to be desired, but thanks to my knowledge of the English language, I've expanded my horizons and worldview quite well.
History of interest in programming: Two months ago, having an overall picture of programming in hand, I decided to delve into iOS development. My cousin, upon learning about my interest in programming, kindly provided me with everything I needed: a new MacBook, iPhone, courses, books, websites, YouTube channels, etc.
Start: The first thing I started with was learning the Swift syntax. I went through all the books, courses, etc. On this topic, even then, I needed to stop and ask someone for help or advice. Because I didn't understand anything at all. To this day, I still don't understand all these sophisticated phrases, explanations, and terms. Separate searches on Google for everything said above only confuse me.
Questions: Am I too stupid for this game? Should I start over and study 5th-grade math? Or is there some kind of Bible for ultra-beginners where everything is laid out step by step?"
I have an user which is complaining about the notification badge that appear on the app icon.
If he disables it in the badge switch in “settings -> Notifications -> App name” will he still be able to receive push notifications? If yes, Is there any configuration that needs to be done programmatically?
I wrote an xctest to validate my code that converts a SwiftUI Color to a hexadecimal string. Locally, this test passes because Color.red has a hex value of "#FF453AFF".
However, it fails in Xcode Cloud because the hex value is different.
I have run the testing a few times to make sure my code wasn't deterministic but the hex values are stable, just wrong. I also confirmed that locally I'm using iOS 17.2 which is the same version being use in Xcode Cloud. I considered maybe Apple updated the Color.red but it does it with all of the stock Color enum cases. Perhaps my testing method is invalid? Any tips on how to correct this?
Update: the solution was to instantiate a color from RGB. The system won’t modify this like it can sometimes do for the system colors based on context. Tests are passing locally and in the cloud now. Thank you to all that helped sort this.
I am trying to change display resolution setting within an application. I have attempted to list all available resolutions with CGDisplayCopyAllDisplayModes
, but none of the HiDPI modes are listed, and this is already a known limitation of this API. How can I get the HiDPI modes?
I have written an extension on Color and want to write an xctest unit test for it. However, the test does not recognize the extension. What do I need to do in order to grant the test access to that code? Should I add the definition file to the test target or is there a better way to do this?
Hello all,
I’m building a macOS app for a portfolio project in SwiftUI, and I have a RESTful Web Service written in C# running on localhost. My problem lies in that I can’t reach out to it despite the fact that I’m fairly certain that the macOS app and the API would be running on the same localhost context, unlike an iOS app in the simulator. Am I missing something here? Is it some kind of sandboxing thing?
If you press cmd + shift + 5 in macOS and click "capture selected window", you will find out that you can take a screenshot each individual icons on the menu bar. Therefore macOS Screen Capture Kit have the API to record specific icons on the menu bar. (Also, apps like Bartender use it.) However, I am unable find the documentation for this API myself. The issue is that, if I use swift to list windows, menu bar icons are not listed.
Could anyone show/tell me how to write a demo app, screen capturing (recording) the date and time icon in the menu bar and streaming that to a separate window?
[Also posted here: https://www.reddit.com/r/MacOS/comments/18dlv6q]
Hi,
I have a ScrollView in my application in combination with a LazyVStack. The items in the list are only text, but the processing of that text is heavy due to formatting. I have no problem with lists that are about 500 items large, but above that, it becomes noticeably laggy.
My current approach is to load items in batches and then remove items in batches that are no longer visible, and re-load them when the user is scrolling back up, etc. Essentially, it's a form of pagination where I always have one page behind and one page ahead of the currently loaded page in memory. This works quite well in terms of performance. However, the issue arises when I remove earlier items from the list; the scroll position is no longer accurate, leading to jumps in huge and unpredictable item IDs.
Is there a smarter or more "Swifty" way to solve this issue? My current approach would involve calculating the height of each item and, when removing them from memory, replacing them with EmptyViews of the exact height that is now missing. However, this feels a bit too complicated to be the right solution.
Thank you!
When I localized my first iOS app, I created some scripts to translate the strings with GPT-4. I also hired professional translators to proofread the translations, but I had to spend hours copying and pasting the strings back into Xcode.
I decided to create an end-to-end solution with a nice user interface, and the result is Local Hero. You can import your strings from Xcode, translate them with GPT-4, and share links for others to edit your translations. For quality control, you can translate the translations back into the source language. When you've finalized your translations, you can easily import them back into Xcode.
The prompts sent to GPT-4 include the comments associated with your strings for context, and you can also provide additional instructions to ensure more accurate translations. For example, you can instruct the language model not to translate your app's brand name.
If I get a good initial response, I'd like to add support for Android Studio and the most popular web frameworks, as well as some paid features such as a translation memory to maintain consistent terminology across multiple platforms.
I'd love to get feedback from Xcode users on whether this service is useful and how it could be improved. If you haven't started localizing your apps, I wrote a guide with some tips that I've learned along the way. Let me know what you think!
For some reason the token isn't getting set to my server. I get code 50 as a print error, but I can't seem to narrow it down. Do any of you have any idea?
@objc func applePayButtonTapped() {
print("Apple Pay button tapped")
let request = StripeAPI.paymentRequest(withMerchantIdentifier: "merchant.medical.daylike", country: "US", currency: "EUR")
request.paymentSummaryItems = [PKPaymentSummaryItem(label: "Script", amount: NSDecimalNumber(string: "1.00"))]
print("Payment request details: \(request)")
paymentContext = STPApplePayContext(paymentRequest: request, delegate: self)
print("Presenting Apple Pay sheet")
paymentContext?.presentApplePay()
print("yesue")
}
func applePayContext(_ context: STPApplePayContext, didCreatePaymentMethod paymentMethod: StripePayments.STPPaymentMethod, paymentInformation: PKPayment, completion: @escaping StripeApplePay.STPIntentClientSecretCompletionBlock) {
print("Apple Pay did create payment method")
let paymentMethodId = paymentMethod.stripeId
let amount = 100 // Example amount in cents (€10.00)
createPaymentIntent(paymentMethodId: paymentMethodId, amount: amount) { result in
switch result {
case .success(let clientSecret):
completion(clientSecret, nil)
case .failure(let error):
print("Error in creating payment intent: \(error.localizedDescription)")
completion(nil, error)
}
}
}
func applePayContext(_ context: STPApplePayContext, didFailToCreatePaymentMethodWithError error: Error) {
print("Failed to create payment method: \(error.localizedDescription)")
}
func applePayContext(_ context: STPApplePayContext, didCompleteWith status: StripePayments.STPPaymentStatus, error: Error?) {
print("Apple Pay process didCompleteWith status: \(status)")
if let error = error as NSError? {
print("Error in Apple Pay process: \(error.localizedDescription), Code: \(error.code)")
}
print("Apple Pay process completed with status: \(status)")
switch status {
case .success:
// Payment succeeded
break
case .error:
// Payment failed
break
case .userCancellation:
// User canceled the payment
break
@unknown default:
fatalError("Unknown Apple Pay status")
}
}
My prints
Apple Pay button tapped
Payment request details: <PKPaymentRequest: 0x14bde0f80; APIType: PKPaymentRequestAPITypeInApp, requestType: PKPaymentRequestTypeApplePay, requestor: PKPaymentRequestorDefault, countryCode: DE, merchantCapabilities: 1, currencyCode: EUR, shippingType: SHIPPING, applePayLaterAvailability: enabledshouldUseMerchantSession: 0, suppressTotal: 0, paymentSummaryPinned: 0, supportedNetworks: (
AmEx,
MasterCard,
Maestro,
Visa,
Discover
), supportsCouponCode: 0, paymentSummaryItems: 1, requiredBillingContactFields: {(
post
)}, >
Presenting Apple Pay sheet
yesue
Apple Pay process didCompleteWith status: error
Error in Apple Pay process: There was an unexpected error -- try again in a few seconds, Code: 50
Apple Pay process completed with status: error
I want to implement a SwiftData Model in my SwiftPlayground(Xcode) but I can't get it to work. If I copy the code into a normal IOS Project it works fine but in Swift Playground there are IOS version problems. Has anyone experienced the same problems and has a solution? Thanks.
I'm trying to build a collection view layout similar to the Netflix app which has numerous vertical rows on the screen and each row scrolls horizontally to display cells in the row.
With my code as follows, it kind of works except the heading title, which is being set in collectionView.dequeueReusableSupplementaryView(ofKind:withReuseIdentifier:for:)
only displays on every second header and behaves very erratically.
If I set the following, everything runs vertically instead of horizontally but every header has a title:
section.orthogonalScrollingBehavior = .none
If I set section.orthogonalScrollingBehavior
to anything other that .none
, everything runs horizontally (as I want it) but every second row header doesn't have a title.
Is this a bug or am I doing something wrong?
Follows is the pertinent part of my code:
func configureCollectionView() {
let collectionViewLayout = configureLayout()
collectionView = UICollectionView(
frame: view.bounds,
collectionViewLayout: collectionViewLayout
)
//...
collectionView.register(CollectionReusableView.self,
forSupplementaryViewOfKind: "header-supplementary-item",
withReuseIdentifier: "header-supplementary-item")
view.addSubview(collectionView)
}
func configureLayout() -> UICollectionViewLayout {
let badgeAnchor = NSCollectionLayoutAnchor(
edges: [.top, .trailing],
fractionalOffset: CGPoint(
x: 0.5,
y: -0.5
)
)
let badgeSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(0.14),
heightDimension: .fractionalHeight(0.14)
)
let badge = NSCollectionLayoutSupplementaryItem(
layoutSize: badgeSize,
elementKind: "badge-element-kind",
containerAnchor: badgeAnchor
)
let itemSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(0.5),
heightDimension: .fractionalHeight(1.0)
)
let item = NSCollectionLayoutItem(
layoutSize: itemSize,
supplementaryItems: [badge]
)
item.contentInsets = NSDirectionalEdgeInsets(
top: 5,
leading: 5,
bottom: 5,
trailing: 5
)
let groupSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1),
heightDimension: .fractionalWidth(0.5)
)
let group = NSCollectionLayoutGroup.horizontal(
layoutSize: groupSize,
subitems: [item])
group.contentInsets = NSDirectionalEdgeInsets(top: 7,
leading: 0,
bottom: 0,
trailing: 0)
let headerSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .fractionalWidth(0.1)
)
let header = NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: headerSize,
elementKind: "header-supplementary-item",
alignment: .topLeading
)
header.zIndex = -10
let section = NSCollectionLayoutSection(
group: group)
section.contentInsets = NSDirectionalEdgeInsets(
top: 2,
leading: 2,
bottom: 2,
trailing: 2)
section.boundarySupplementaryItems = [header]
section.orthogonalScrollingBehavior = .groupPaging
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 30, trailing: 0)
let layout = UICollectionViewCompositionalLayout(
section: section
)
let config = UICollectionViewCompositionalLayoutConfiguration()
config.contentInsetsReference = .readableContent
layout.configuration = config
return layout
}
func configureDataSource() {
datasource = UICollectionViewDiffableDataSource<Section, AnimalResult>(
collectionView: collectionView) { [weak self]
(collectionView, indexPath, animal) -> UICollectionViewCell? in
//...
}
datasource.supplementaryViewProvider = { [weak self]
(collectionView: UICollectionView,
kind: String,
indexPath: IndexPath) -> UICollectionReusableView? in
guard let self else { return nil }
if kind == "badge-element-kind" {
//...
} else if kind == "header-supplementary-item" {
let headerView = collectionView.dequeueReusableSupplementaryView(
ofKind: "header-supplementary-item",
withReuseIdentifier: "header-supplementary-item",
for: indexPath) as! CollectionReusableView
let sections = datasource.snapshot().sectionIdentifiers
let section = sections[indexPath.section]
let randomWords = ["apple", "bicycle", "candle", "dolphin", "elephant", "flamingo", "giraffe", "harp", "island", "jigsaw", "kangaroo", "lemon", "mango", "notebook", "ocean", "parrot", "quasar", "radiator", "sunflower", "tornado", "umbrella", "violin", "waterfall", "xylophone", "yogurt", "zeppelin"]
headerView.title.text = randomWords.randomElement()?.uppercased()
headerView.backgroundColor = .systemGray2.withAlphaComponent(0.5)
return headerView
} else {
return nil
}
}
var snapshot = NSDiffableDataSourceSnapshot<Section, AnimalResult>()
//...
datasource.apply(snapshot, animatingDifferences: false)
}
I want to be able to use iCloud entitlement in Command Line Tool in my macOS application but how do I do that? When trying to add the entitlement it doesn’t up like in my other extensions.
And also, how do I allow other process to use my command line tool in my application? When I add the Sandbox entitlement other processes don’t have access to run it whereas without that entitlement they can.
Hey, Reddit community!
Exciting news—I've just launched my very first app on the App Store!
📱 Presenting SymbolLister 🎨, a tool to simplify font and symbol exploration for designers and developers. I'm eager to hear your thoughts and feedback.
💡 Key Features:
🚀 Download SymbolLister now on the App Store: https://apps.apple.com/us/app/symbollister/id6473278219
I'm also open to questions and feedback, so feel free to share your thoughts!
Below are iOS gpt's based on each of Apple's most popular frameworks and app services.
Coming soon...
Requires an OpenAI GPTPlus account
Hows it work?
- Naive RAG based on the out-of-the-box retrieval by OpenAI. THat means the larger the framework (eg. foundation, swiftUI), the less effective the retreival is, but it's still much better than the base model.
Why launch this?
I am launching this to see if theres demand to invest time into building out a few pipelines for scraping, processing, upserting, and embedding. That would make the retrieval and code-gen a lot better.
As somebody who has never even touched swift, I am looking to learn it to make a project to hopefully beef up my resume a little bit. The project I’m aiming for to me seems a bit complex for a complete beginner to the language. I am aiming to make a chat-room type app, kind of like discord, with different sections for different purposes. I’d like to be able to handle multiple users, and 1-1 PMing.
All of that to ask, how far in over my head am I with this idea, if at all? I have most of December to dive deep into this project.