Post

Replies

Boosts

Views

Activity

Define Array of protocol which conforms to Identifiable
I've got Yet Another Protocol Question. Sorry, folks.The Swift 5.1 manual describes creating a `Collection` where the `Element` is a simple protocol, but doesn't explain how to make a Collection where the Element is a protocol with an associatedtype. In my case it's a protocol `Playable` that requires conformance to `Identifiable`.I am fine with requiring the `Identifiable.ID` type to be `Int` for all types which adopt `Playable`, but I don't know how to express that qualification/requirement. The bits hit the fan when I try to declare something to be `[Playable]`.My playground code might make my question clear.protocol Playable: Identifiable // DOESN'T WORK where ID: Int { // DOESN'T HELP associatedtype ID = Int // DOESN'T HELP var id: Int { get } func play() } struct Music: Playable { var id: Int func play() { print("playing music #\(id)") } } (Music(id: 1)).play() // displays: "playing music #1\n" class Game: Playable { var id: Int init(id: Int) { self.id = id } func play() { print("playing game #\(id)") } } (Game(id: 2)).play() // displays: "playing game #2\n" enum Lottery: Int, Playable { case state = 100 case church case charity var id: Int { return self.rawValue } func play() { print("playing lottery \(self) #\(self.rawValue)") } } Lottery.church.play() // displays: "playing lottery church #101\n" var stuff: [Playable] = [] // error: Protocol 'Playable' can only be used as a generic constraint because it has Self or associated type requirements stuff.append(Music(id: 10)) stuff.append(Game(id: 24)) stuff.append(Lottery.charity) stuff.map { $0.id }My goal is to have different structs and classes conforming to Playable (and hence to Identifiable) able to live inside a Collection.
7
1
7.6k
Nov ’22
Dragging list rows between sections
I am making an iPhone-first app which has a 2 level data structure. I want the user to be able to drag List rows from section to section, but not reorder the sections. Is there a SwiftUI way to do it, or should I resort to UIKit? The basic problem seems to be that ForEach.onMove only allows reordering within its nearest datasource. That seems sensible as a general facility. As it stands now drags can only happen within a section. Swift ForEach(groups) { group in Section(header: Text(group.text)) { ForEach(group.items) { item in Text(item.text) } } } .onMove { … } I might be willing to dive into UIKit to get this done, if it'll handle it. Right now I've flattened the data and marked some items as "containers" and others as "leaves". All get emitted as a dumb flat list: Swift ForEach(items) { item in if item.isContainer { Text(item.text).bold() } else { Text(item.text) } } .onMove { … } The major downside is users can move the container "section header" lines. Drag and drop doesn't seem to work on iPhone, just iPads. I'm kinda shy about hierarchical lists using List(_,children:) because I expect move would still allow top level items (my containers) would be allowed to be moved.
4
0
5.5k
Jul ’21
Attempt to map database failed
This looks like a refresh of an old question. I'm using iOS 15 beta 7 and have presented a UIActivityViewController from a SwiftUI app. I get a ton of these errors when trying to share a two-item list containing String and UISimpleTextPrintFormatter. [default] LaunchServices: store (null) or url (null) was nil: Error Domain=NSOSStatusErrorDomain Code=-54 "process may not map database" UserInfo={NSDebugDescription=process may not map database, _LSLine=264, _LSFunction=-[_LSDReadClient getServerStoreWithCompletionHandler:]} [default] Attempt to map database failed: permission was denied. This attempt will not be retried. [db] Failed to initialize client context with error Error Domain=NSOSStatusErrorDomain Code=-54 "process may not map database" UserInfo={NSDebugDescription=process may not map database, _LSLine=264, _LSFunction=-[_LSDReadClient getServerStoreWithCompletionHandler:]} [default] -imageForImageDescriptor: can do IO please adopt -imageForDescriptor: for IO free drawing or -prepareImageForDescriptor: if IO is allowed. (This will become a fault soon.) [default] LaunchServices: store (null) or url (null) was nil: Error Domain=NSOSStatusErrorDomain Code=-54 "process may not map database" UserInfo={NSDebugDescription=process may not map database, _LSLine=264, _LSFunction=-[_LSDReadClient getServerStoreWithCompletionHandler:]} It looks as if the API is checking for entitlements I haven't requested, but I am not trying to share images. I just want to share text as plaintext or a nicely formatted printable attributed string.
4
3
7.3k
Aug ’21
Using KeyFrameTimeline as value for .keyFrameAnimator view modifier
I have several views I want to animate in concert. I plan to use keyframe animation. I want to keep the .keyFrameAnimator modifier code small; I have a lot of ...Keyframes inside several KeyframeTracks. It seems like I should be able to isolate the body of the keyframes parameter into a func or var. Builders are such a pain, I can't grok the right way to refactor their bodies out. I've tried to make a standalone @KeyframeTrackContentBuilder<MyValue> function but cannot figure out the right syntax/incantation to stuff it with KeyframeTracks. My latest attempt is to create a func that returns a KeyframeTimeline, but that's been a deadend too. let k: KeyframeTimeline<MyValue> = timeline(...) CartoonCardView(color: .yellow) .keyframeAnimator( initialValue: k.value(time: 0) ) { content, value in content .rotationEffect(value.angle) .scaleEffect(value.scale) .offset(value.offset) } keyframes: { _ in k } The error on k in the last line is "No exact matches in call to static method 'buildExpression'" with the sub-error "Candidate requires that 'KeyframeTimeline' conform to 'KeyframeTrackContent' (requirement specified as 'K' : 'KeyframeTrackContent') (SwiftUICore.KeyframesBuilder)"
4
0
956
Jul ’24
searchable: Add an auxilliary search view
Is there a clean way to add an auxilliary view to the SwiftUI .searchable view? The best I have found is to add a VStack above the list being searched, but this makes the removal transition behave funny. ("Funny" means the search view and aux views animate away fine, but after they finish animating the List view snaps to the top of the screen, hiding the idle search field. The normal behavior leaves the idle search field showing.) NavigationStack { MyListView().searchable(...) } ——— struct MyListView: View { @Environment(\.isSearching) private var isSearching var body: some View { if isSearching { VStack {...my auxilliary view...} } List {...} } }
Topic: UI Frameworks SubTopic: SwiftUI
3
0
450
Sep ’24
How can I view the Development-server private data for my iCloud test account in the CloudKit Dashboard?
When developing a CloudKit application, the standard recommendation is to create an iCloud account for testing. That makes a lot of sense as I’d like to keep developing code far from my personal iCloud account. But the CloudKit Dashboard won’t let me view the private database for that account. What do other people do to check their work?* clarification: I mean on the development server, not the production server.
3
0
1.7k
Dec ’22
UICollectionViewCell subclass cannot use backgroundView property?
I made a subclass of UICollectionViewCell and Swift is complaining that I'm not allowed to use superclass properties like bounds, backgroundView or selectedBackgroundView. This very code was given by Appleʼs documentation - https://developer.apple.com/documentation/uikit/uicollectionviewdelegate/changing_the_appearance_of_selected_and_highlighted_cells so I don't understand why it's disallowed. I declared class MyCollectionViewCell: UICollectionViewCell method awakeFromNib. class MyCollectionViewCell: UICollectionViewCell { ... override class func awakeFromNib() { ... let redView = UIView(frame: bounds) redView.backgroundColor =  colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) self.backgroundView = redView let blueView = UIView(frame: bounds) blueView.backgroundColor =  colorLiteral(red: 0, green: 0, blue: 1, alpha: 1) self.selectedBackgroundView = blueView Xcode 12.2 gives an error about bounds, backgroundView, and selectedBackgroundView saying stuff like "Instance member 'bounds' cannot be used on type 'MyCollectionViewCell'". If I declare a variable as UICollectionViewCell I can set these properties in it, but a function in a subclass of UICollectionViewCell cannot access its own properties?
2
0
880
Dec ’20
(Xcode 14.0 beta 5) ThreadSanitizer: CHECK failed: tsan_platform_posix.cpp:83 "((beg)) <= ((end))"
Similarly to this old post [https://developer.apple.com/forums/thread/130969] I am getting a "ThreadSanitizer: CHECK failed" before my code seems to have launched. Is this something I should spend time trying to reproduce in a small project or is it an Xcode bug others are getting too? Turning off the sanitizer is my dirty workaround for now.
2
0
3.0k
Aug ’22
ShareLink FileRepresentation exports message as a file
When I save an item which is a FileRepresentation to the File system/Files app, TWO files are saved: the shared file, and simple text file containing the message text. I don't want the user to get the message in a text file when they save that way. Sure I can just leave out the message parameter, but then it's useful if they want to email the file somewhere? Is there a way to have a message text that isbn't saved in a file? ShareLink(item: ..., subject: Text("..."), message: Text("..."), //⬅ this text gets saved in a 2nd file preview: SharePreview("...", image: ...)) { Label { Text("...") } icon: { Image(systemName: "square.and.arrow.up") } }
2
0
835
Nov ’23
Single window keyboard shortcut
I made a macOS document-based app that has a second scene that's a Window. It's name appears in the single window list of the Windows menu, but has no assigned shortcut. I've tried the following to assign a shortcut to it, but it doesn't add a "⌘L" as I want: Window("Logs", id: "logs") { LogsView() } .keyboardShortcut("l") I can brute-force this using .commands to replace the menu item but that seems crude and unnecessary. Is it the only way?
2
0
476
Jan ’25
Provide custom "sharing" activity to other apps
I want my app to receive certain data types shared from other apps. I'm interested in text and URLs today, and maybe images later. UIActivity seems to be the way to start but I don't know what to do with the subclass I've created. I assume it at least needs to be declared in the app's properties, but I don't know where to read about that and nothing stands out in the project editor. I don't know the API or keywords to do my research, so if anyone can point me I'll appreciate it.
1
0
1k
Feb ’21
Does Publisher.first complete after sending a value?
I would like the first() operator to send a value as soon as it's received a value that satisfies the condition (and to finish publishing as well). But I don't know how to test this is really happening. The only test I've devised is below, but I suspect it is wrong. The map operator will keep demanding values of course, so I expect it to print all of them. Yet the sink subscriber doesn't invoke receiveValue or receiveCompletion until after map is done, which suggests first is awaiting upstream completion. Does first really does need the upstream to complete before it sends anything onward? What's really the story here for first? import Foundation import Combine let numbers = (-10...10) let cancellable = numbers.publisher     .map({ n in         Thread.sleep(forTimeInterval: 1)         print("sending \(n)")         return n     })     .first { $0 0 }     .sink { completion in         switch completion {         case .failure(_): print("failed")         case .finished: print("finished")         }     } receiveValue:  { print("\($0)") } My specific situation is I'm monitoring for when the network becomes available the first time. Of course the monitoring source will never (should never) finish but I do want completion for a pipeline subscribing to that monitor with first.
1
0
927
May ’21