/r/swift

Photograph via snooOG

Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

ATTN! Looking for work or to hire? Check out r/SwiftJobs!


About:

Dedicated to the Swift programming language released by Apple. More info in the Swift Wiki.

Please, check the FAQs before submitting.


IRC Chatrooms:

General Swift Discussion

irc.freenode.net #swift-lang

Cocoa/Cocoa Touch Discussion

irc.freenode.net #cocoa-init

Related Subreddits:


Keywords: swift, swiftlang, ios, os x, apps, apple, mac, iphone, ipad

/r/swift

113,060 Subscribers

1

Install on Fedora? (Redhat)

I wanted to try out the swift language today but did not find any clear instructions on how to install it on linux for fedora, which uses redhat. Anyone know how to do this?

1 Comment
2024/04/07
02:21 UTC

0

2020 M1 MacBook Pro Good Enough for Learning Swift?

I just bout a 2020 M1 512gb SSD 8gb ram for $600 to learn swift with.

Will this machine be good enough to both learn what I need to learn for app making and also carry over into actually making the app?

9 Comments
2024/04/07
00:32 UTC

2

Have you considered moving to React Native or Flutter? Shall we move our native team to cross-platform?

I started my career in iOS. I later moved to macOS apps & tvOS apps. Started with objective C and moved to Swift.

In 2015 - I started my dev agency specializing on native iOS apps. I attended WWDC and running a apple developers community online.

Slowly we have grown to full-stack agency with web, native apps & cross-platform apps.

We are 12 native developers iOS and android. We are mainly maintaining old apps and building very few new apps.

Lately, we are seeing cross-platform apps are in more demand from clients perspective. We are not seeing this trend reversing. Are you?

Looking forward to learn your views.

Edit: we are grown to 70 people team. Focusing on niche like fintech, sports, fitness, legal etc.

16 Comments
2024/04/06
22:41 UTC

0

Apple example code is wrong

I'm using a bit of example code from Apple

    func random() -> CIImage {
       let randomGenerator = CIFilter.randomGenerator()
       return randomGenerator.outputImage!
    }

but I get an error that CIFilter.randomGenerator() doesn't exist

what do I have to import to use CIfilters. I'm already importing CoreImage

2 Comments
2024/04/06
21:49 UTC

1

How do I display the wind speed from WeatherKit?

Hi everyone!

I have been working with weather kit recently. I fairly new to Swift and am having trouble figuring out how to get the wind speed from Weather kit. I know it might sound a little silly asking about the wind speed specifically, but a lot of the other features such as the temperature are shown in the tutorials that I have looked at but for some reason I haven't seen one that included wind speed. I would really appreciate it if someone could please show me how to display it on the screen.

Thank you!

0 Comments
2024/04/06
20:53 UTC

2

Swift playgrounds

So I started to teach myself how to code using Swift Playgrounds and I was wondering if I should skip Get Started with Code and go straight to Learn to Code 1? I've heard people say that Get Started with Code is incomplete and doesn't really explain how to do things.

View Poll

1 Comment
2024/04/06
18:39 UTC

4

My First Swift App!

Hey Everyone, just released my first Swift app and would love for you guys to check it out and give some feedback! It's a simple tourism app I made for my state that lists some towns, state parks, and restaurants, and also events that are happening (still in the process of adding more data). I hope to add some features that actually differentiate it from just using google/apps like yelp or trip advisor, but it was still a great way to learn IOS Development. Thanks!

App Store URL: https://apps.apple.com/us/app/jersey-journeys/id6480574525?platform=iphone

https://preview.redd.it/pgs967cwuvsc1.png?width=2732&format=png&auto=webp&s=5b25baed8c9707d93257fe31bc332a12d33fbb02

0 Comments
2024/04/06
16:08 UTC

8

Is it just me or is Xcode’s version control unusable?

I’m the only one working on my basic project (no one else is pushing changes!), yet I still get merge conflicts. When I try to resolve the conflict, it says the conflicting file doesn’t exist in my local repository. At this point I need to re clone the repo only for this to eventually happen again… does anyone else get these weird issues? I’m reasonably familiar with git/github and have used it for years without issues, but the Xcode version seems like a horrendous buggy mess. Back to the command line I guess.

23 Comments
2024/04/06
15:17 UTC

167

My iOS App Generator is now used by over 40 iOS developers. Thanks Reddit.

Almost exactly a month ago, I released SwiftyLaunch. It’s an iOS App generator that allows you to select all the functionality that you might need in your next iOS App and it would generate an iOS Starter Project with these things already configured for you.

Things like the complete Auth Flow, In-App Purchases, Push Notifications, Setup & Connection with Backend and DB, and more. You just select all the "tedious" things to setup and we do it for you automagically (sorry for the cheesiness). This way you can focus on what makes your App unique, and not on setting up the Sign-In Flow again for the 10th app in a row!

The launch was as great as it was a disaster. Every couple of hours I'd have a crisis to fix. Some of my favorite ones:

  • Support/Contact emails not even working for the first 3 days
  • App Generation failing on over 50% of users devices
  • Users were able to circumvent my license screen by simply pressing ESC (it was a sheet, and I didn’t know that on Mac it was automatically dismissible without explicitly stating .interactiveDismissDisabled()!!

But now, just a month down the road, SwiftyLaunch was already used to launch 6 (!) iOS Apps on the App Store. These Apps have already generated cumulatively just over $4,500 in revenue. It’s insane!

Reddit was the first place I promoted SwiftyLaunch and got my initial purchases. This is also the place where I always found interesting post and articles that helped me become a better Developer and where I made some very good iOS Dev-friends! Thanks so much for being such an amazing community.

Now, to the interesting part: You guys are incredible. You build insane things that people use and love every day. I want to give back. This is why I am going to give away 3 SwiftyLaunch Ultra (worth $199 with the Launch Discount) to the three most upvoted comments idea saying what you’re going to build with this. And better yet, build it in public and share your experiences and struggles, your victories and defeats.

In simple words: Write your next iOS App idea. 3 most upvoted comments will receive a free SwiftyLaunch Ultra license to build this idea. Winners will be selected in exactly one week, on April 13th.

Enjoy!
-Vladislav

https://preview.redd.it/k138i135fvsc1.png?width=2758&format=png&auto=webp&s=b623633bba1980e4b89daee3696c46ae354593d5

42 Comments
2024/04/06
14:40 UTC

0

Why would a Swift iOS developer buy a MacBook Pro with an M3 Pro instead of one with an M3?

Is there really a noticeable difference in speed when developing iOS apps/games in Swift?

Isn't the M3 MacBook Pro a better value?

44 Comments
2024/04/06
12:23 UTC

1

What is your way of upgrading your swift code to the next version?

Do you let the newest version of Xcode to do it or do you update the swift code manually?

7 Comments
2024/04/06
10:03 UTC

0

Want to learn Swift with basic knowledge of Python and C++

I want to start learning iOS programming. I have some basic knowledge of Python and C++. Do any of you have any recommendations on how to learn Swift?

7 Comments
2024/04/06
06:44 UTC

2

Swift Student Challenge Award Shipping Time?

Congrats to all the winners this year! It’s my first time winning and was curious to know how long it usually takes for Apple to send the student swift challenge winner awards/gifts? Living in Canada 🇨🇦

0 Comments
2024/04/06
03:14 UTC

2

Changing SwiftData storeURL

Hey Guys,

I want to store my app's users' data into separate sqllight files, hence if a user logs out and logs in with a new email, I want his own data being loaded, I tried changing ModelContainer but it does not sound effective (perhaps because the context in different views still having old data?). What is the right way to handle the switch?

0 Comments
2024/04/06
01:13 UTC

3

My alternative to Quizlet (way cheaper vocab trainer)

All students probably know Quizlet and other vocab trainers and how they charge 7$ per month. I just published my first app on the Apple AppStore. It's called TurboTerms and it charges 99ct or 1.99$ ONE TIME depending on your region. After that you never have to pay again and you receive constant updates. If you're interested, heres the link:

https://apps.apple.com/us/app/turboterms/id6479650868

https://preview.redd.it/zck2y7bymosc1.png?width=770&format=png&auto=webp&s=bace3b85aaded9cbc234ad3ea2b4e4a847d818f3

0 Comments
2024/04/05
15:51 UTC

1

Having trouble retrieving Set from Keychain

Hi guys,

retrieveTransactionsFromKeyChain(completion:) wither crashes or returns nil.

If keychainDictionary contains kSecMatchLimit: kSecMatchLimitAll it returns nil.

If keychainDictionary contains kSecMatchLimit: kSecMatchLimitOne it crashes.

What am I not getting about this?

Here is my code:

private func saveTransactionToKeyChain() {
        keychainQueue.async { [weak self] in
            guard let self else { return }
            if let tempTransactionID {
                retrieveTransactionsFromKeyChain { retrievedTransactionArray in
                    var transactionArray: Set<UInt64> = []
                    if let retrievedTransactionArray {
                        // If it exists, append to it and save...
                        transactionArray = retrievedTransactionArray
                        transactionArray.insert(tempTransactionID)
                    } else {
                        // If it doesn't exist, create it and save...
                        transactionArray.insert(tempTransactionID)
                    }
                    
                    let data = withUnsafeBytes(of: transactionArray, { Data($0) })
                    
                    let keychainDictionary: CFDictionary = [
                        kSecClass: kSecClassKey,
                        kSecAttrApplicationLabel: Constants.transactionsKey,
                        kSecValueData: data,
                        kSecReturnData: kCFBooleanTrue as Any ] as CFDictionary
                    let osStatus = SecItemAdd(keychainDictionary, nil)
                    self.printOSStatus(osStatus)
                }
                self.temporaryTransaction = nil
                self.tempTransactionID = nil
                
            }
        }
    }

internal func retrieveTransactionsFromKeyChain(completion: @escaping (Set<UInt64>?) -> Void)  {
        keychainQueue.async { [weak self] in
            guard let self else { return }
            let keychainDictionary: CFDictionary = [
                kSecClass: kSecClassKey,
                kSecAttrApplicationLabel: Constants.transactionsKey,
                kSecMatchLimit: kSecMatchLimitAll,
                kSecReturnData: kCFBooleanTrue as Any] as CFDictionary
            
            var item: CFTypeRef?
            //let osStatus = SecItemDelete(keychainDictionary)
            let osStatus = SecItemCopyMatching(keychainDictionary, &item)
            printOSStatus(osStatus)
            if let item,
               let data = item as? Data {
                let retrievedTransactions = data.withUnsafeBytes({ $0.load(as: Set<UInt64>.self) }) as Set<UInt64>
                completion(retrievedTransactions)
            } else {
                completion(nil)
            }
        }
    }
    
    let keychainQueue = DispatchQueue(label: "well-spotted-keychain-dispatchqueue", qos: .background)
    
2 Comments
2024/04/05
15:35 UTC

3

Swift Playgrounds for Mac limitations

I used the search bar for this question but most posts were old, so here’s my question :Can you deploy apps to the iPad and iPhone app stores using Swift Playgrounds on a Mac?

3 Comments
2024/04/05
15:00 UTC

29

Been building the first-ever sports social network for a while. Any feedback on UI before I release the app?

29 Comments
2024/04/05
05:20 UTC

3

Mac pro m1 vs mac air m2

I can not decide which one to choose. I am a flutter, and backend developer and started to learn swift. Which one of these is better if they have the exact same price, ram and storage.

12 Comments
2024/04/05
04:16 UTC

1

Printing Unscalable PDF's in iOS Swift

I'm trying to have users print fiducial markers from my Swift application with fixed sizes and known dimensions for a Computer Vision application. It seems nearly impossible to somehow setup the iOS print job such that the PDF doesn't get scaled in some way.

I would rather not have users have to export to another device where they would then have to manually set up the print job to ensure that no scaling occurs. Any advice on how to accomplish this? I've tried messing with the UIPrintPageRenderer
but the documentation on this is lacking and it generally just behaves extremely cryptically, scaling and stretching in unpredictable behaviors.

I've also made sure that the PDF is formatted for US Letter and that there is no content within an inch of the edges of the paper.

0 Comments
2024/04/05
00:53 UTC

0

SwiftUi Newbie

hello guys! just want to ask if where can I able to see latest basic swiftui tutorials? on youtube I can see they are a little outdated. pls help.

8 Comments
2024/04/05
00:42 UTC

7

Any chance AI / Auto-documentation could be coming to XCode in the near future?

I would love to have a feature that automatically generates documentation for functions / classes that is native to XCode. I could just copy all my code into chat gpt, but I feel like it’ll take too much work. Is there any plan of this happening? Or is this just pure optimism on my end?

12 Comments
2024/04/04
23:51 UTC

1

MP3 file locally

I am coding a meditation kind app and I’ll play no-copyright relaxing musics. There will be 22 mp3 files(5 min each.) Is it logical to use assets folder directly or should I try to fetch them from internet? I don’t want to increase the size of app itself.

3 Comments
2024/04/04
22:35 UTC

2

How do you know if a video is playing or not in in avplayer?

I'm building a video player for a react native applications. There are 3 pieces of info I want to shuttle from the swift side to the react native side.

  • current time
  • whether the video has reached the end (ie not paused)
  • if the video is currently playing

I've figured out how to add an observer to the player that sets the current time of the video so what I'm trying to figure out now is how to "listen" for the play/pause/end events. Not necessarily even just the tap of the play button but if the video also stalled from a poor connection.

So basically I'm trying to figure out how to listen for the current status of the video playing.

Here is the code I've written so far:

import Foundation
import AVFoundation
import AVKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        var blackSquare: UIView
        blackSquare = {
            let black = UIView()
            black.translatesAutoresizingMaskIntoConstraints = false
            return black
        }()
        let BCPlayer = StreamingVideoPlayer()
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        blackSquare.backgroundColor = .red
        view.addSubview(blackSquare)
        addConstraints()
        
        let m3u8: URL = URL(string: "https://demo.unified-streaming.com/k8s/features/stable/video/tears-of-steel/tears-of-steel.mp4/.m3u8")!
        BCPlayer.add(to: blackSquare)
        BCPlayer.play(url: m3u8)
        
        func addConstraints() {
            var constraints = [NSLayoutConstraint]()
            constraints.append(blackSquare.leadingAnchor.constraint(equalTo: view.leadingAnchor))
            constraints.append(blackSquare.trailingAnchor.constraint(equalTo: view.trailingAnchor))
            constraints.append(blackSquare.bottomAnchor.constraint(equalTo: view.bottomAnchor))
            constraints.append(blackSquare.topAnchor.constraint(equalTo: view.topAnchor))
            NSLayoutConstraint.activate(constraints)
        }
    }
    
   

}

class StreamingVideoPlayer {
    private let playerViewController = AVPlayerViewController()
    private let avPlayer = AVPlayer()
    
    var playbackTitle: String = ""
    var playbackArtist: String = ""
    var playbackArtwork: String = ""
    
    var isPlaying: Bool
    var currentTime: Double
    var hasEnded: Bool
    var timeObserver: Any? = nil
    
    private lazy var playerView: UIView = {
        let view = playerViewController.view!
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    public init() {
        self.currentTime = 0.0
        self.isPlaying = false
        self.hasEnded = false
        setObserverToPlayer()
    }

    private func setObserverToPlayer() {
        let interval = CMTime(seconds: 0.3, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
        timeObserver = avPlayer.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main, using: { elapsed in
            self.updatePlayerTime()
        })
    }
    
    private func updatePlayerTime() {
        let currentTime = self.avPlayer.currentTime()
        let currentTimeInSecond = CMTimeGetSeconds(currentTime)
        self.currentTime = currentTimeInSecond
        print(self.currentTime)
    }
    
    public func add(to view: UIView) {
        view.addSubview(playerView)
        NSLayoutConstraint.activate([
            playerView.topAnchor.constraint(equalTo: view.topAnchor),
            playerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            playerView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            playerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        ])
    }
    
    public func play(url: URL) {
        let asset = AVAsset(url: url)
        let playerItem = AVPlayerItem(asset: asset)
        avPlayer.replaceCurrentItem(with: playerItem)
        playerViewController.player = avPlayer
        playerViewController.player?.play()
        setupMetadata()
    }
    
    public func pause() {
        
    }
    
    private func setupMetadata() {
            let title = AVMutableMetadataItem()
            title.identifier = .commonIdentifierTitle
            title.value = playbackTitle as NSString
            title.extendedLanguageTag = "und"

            let artist = AVMutableMetadataItem()
            artist.identifier = .commonIdentifierArtist
            artist.value = playbackArtist as NSString
            artist.extendedLanguageTag = "und"

            let artwork = AVMutableMetadataItem()
            setupArtworkMetadata(artwork)

            // Set external metadata for the current AVPlayerItem
            avPlayer.currentItem?.externalMetadata = [title, artist, artwork]
    }
    
    private func setupArtworkMetadata(_ artwork: AVMutableMetadataItem) {
            if let image = UIImage(named: "Artist") {
                if let imageData = image.jpegData(compressionQuality: 1.0) {
                    artwork.identifier = .commonIdentifierArtwork
                    artwork.value = imageData as NSData
                    artwork.dataType = kCMMetadataBaseDataType_JPEG as String
                    artwork.extendedLanguageTag = "und"
                }
            }
        }
    
}

2 Comments
2024/04/04
17:50 UTC

0

Use Swift and SwiftUI on VSCode in Windows?

Hello, my first post here and I'm sorry if the question is as stupid as it seems but it's still my question.

Is it possible for me to program using Swift and SwiftUI, obviously with a plugin, in VS Code on Windows?

I understand that I won't be able to compile the application and therefore I thought about using MacInCloud, I understand that this is a "hack" but it's because I live in a 3rd world country and the MacBook here is very expensive, I'm struggling to be able to buy one , in the meantime I would like to know if a "hack" like this would work.

Thank you kindly for every response.

9 Comments
2024/04/04
14:12 UTC

196

The man, the myth, the legend.

9 Comments
2024/04/04
12:08 UTC

0

Unable to Get App Store Approved for 1 Month

Looking for anyone who has

  1. released an app in the current year and had repeated app store submission issues out of thin air
  2. or has had a submission wait in review for over a week

I released an app last year. For months I was able to send updates and get approved with fairly little friction. Mar 12, 2024 I submitted a build that got rejected. I made subsequent fixes and submissions that were rejected again the following day, twice on the 14th, and the 16th. Most of all the rejections were inaccurate metadata and minimum functionality. Which is odd because the app has existed virtually the same way since last year, when getting approved was not a problem. The only difference as of recent is we've had a tiktok go viral and led the app to start charting.

On the 17th I made a submission that fulfilled all requirements. I was marked "In Review" from the 17th to the 23rd. Yes a full week. I canceled my submission on the 7th day and resubmitted with a change I thought they'd potentially look for. It has been "Waiting for Review" since then. Going on 14 days.

I contact support every 3 days however they've only responded once, saying they are "proceeding with an expedited review" however it's never shifted to in review.

7 Comments
2024/04/04
11:12 UTC

1

Help understanding how to add value to buttons

I'm a frontend web developer who is trying to get into Swift and iOS in general. I'm currently trying to make a tictactoe game with UIKit. I used storyboard to place a bunch of buttons that I plan on using to trigger a placement.

However, my plan was to make the buttons blank, but upon press either place an 'X' or a 'O' depending on who's turn it is.

Now my issue is, how do I do the equivalent of 'data-attributes' or 'value' in html in swift?

I've read the documentation (skimmed, admittedly) and tried searching. But as far as I've read I can pass tags (which are integers only) and the title and styling of the button to a function.

Basically I want the upper left button to have the value of '0,0', but button next to that '0,1' and I want to pass these values to a function.

I'm at a loss atm

12 Comments
2024/04/04
02:50 UTC

1

Memory management help

I am coding my own app for app store. I don’t use any libraries except revenuecat. And app memory usage is 1.25 gb at launch. Sometimes even it can crash. What should I pay attention for better usage? Is 1,25 a lot?

30 Comments
2024/04/03
20:30 UTC

11

Is there any reusable Swift UI component library or website?

Any recommendation?

8 Comments
2024/04/03
20:27 UTC

Back To Top