Post

Replies

Boosts

Views

Activity

Reply to Semaphore
Ok, what is the best practice other than async/wait as I have to implement before this fall. Already written: Use completion handler properly Something like this: class A { func aMethod() { B().download(downloadedData: { data in guard let data = data else { return } //Use `data` here... }) } } class B { func download(downloadedData: @escaping (_ data: Data? ) -> Void ) { NetworkManager().downloadRequest {result in switch result { case .success(let data): //..... downloadedData(data) case .failure(let error): print(error) //... downloadedData(nil) } } } } There's one simple principle: Never try to use asynchronous methods synchronously. You may want to use semaphores when you have multiple background threads and make them work together with some limited resources. But never for just waiting an asynchronous task to finish.
Topic: Programming Languages SubTopic: Swift Tags:
Jul ’21
Reply to Semaphore
Are you saying using semaphores to wait until download is complete a bad practice? Sure.  If so, can you suggest a good practice? Use completion handler properly, or async/await if you can target new OSs coming this fall.
Topic: Programming Languages SubTopic: Swift Tags:
Jul ’21
Reply to Swift for server-side
There's no server side frameworks for Swift by Apple. And you would not be able to find any frameworks as widely used as .NET as of now and in the near future. I'm quite critical if Apple would support server-side Swift in the future. You should better visit swift.org (especially Swift on Server) and all related articles on the web.
Topic: Programming Languages SubTopic: Swift Tags:
Jul ’21
Reply to Semaphore
Class c issues semaphore wait That's a super-bad practice in programming iOS or macOS (or any other GUI platforms that main thread may have special meaning). You need to find another way than using semaphore.
Topic: Programming Languages SubTopic: Swift Tags:
Jul ’21
Reply to Calling similar Functions from different classes without protocols
Using a generic method as a protocol requirement may often be a mistake and you would find things would not work as you expect. And predict(input:) and predict(cool:) are different methods, so you cannot define a single simple protocol. (And they do not throws.) An example of defining the two classes and the protocol would be something like this: class One { func predict(input: Int) -> Double { // Code return 0 } } class Two { func predict(cool: Int) -> Int { // Code return 0 } } protocol ModelProtocol { associatedtype Input: Numeric associatedtype Output func prediction(input: Input) throws -> Output } extension One: ModelProtocol { func prediction(input: Int) throws -> Double { predict(input: input) } } extension Two: ModelProtocol { func prediction(input: Int) throws -> Int { predict(cool: input) } } With above prepared, you can write something like this; class Consumer<Consumed: ModelProtocol> { let model: Consumed init(model: Consumed) { self.model = model } func anyFunction() { _ = apply(fn: self.model.prediction(input:), arg: 4) } } // Generic Apply Method func apply<T, V>(fn: (T) throws -> V, arg: T) -> V? { do { return try? fn(arg) } } Or, there may be some better ways, but with your simplified classes shown, I cannot say what would be better.
Topic: Programming Languages SubTopic: Swift Tags:
Jul ’21
Reply to NSTextField delegate methods not getting called
As far as I checked, your Coordinator does not have any methods defined in NSTextFieldDelegate. You should better try something like this: extension OrderedTextField { class Coordinator: NSObject, NSTextFieldDelegate { @Binding var text: String var newSelection: (Int) -> () = { _ in } init(text: Binding<String>) { print("Initializing!") _text = text } func textField(_ textField: NSTextField, textView: NSTextView, candidatesForSelectedRange selectedRange: NSRange) -> [Any]? { print(#function) return nil } func textField(_ textField: NSTextField, textView: NSTextView, candidates: [NSTextCheckingResult], forSelectedRange selectedRange: NSRange) -> [NSTextCheckingResult] { print(#function) return candidates } func textField(_ textField: NSTextField, textView: NSTextView, shouldSelectCandidateAt index: Int) -> Bool { print(#function) return true } func controlTextDidBeginEditing(_ obj: Notification) { print(#function) } func controlTextDidEndEditing(_ obj: Notification) { print(#function) } func controlTextDidChange(_ obj: Notification) { print(#function) } func control(_ control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool { print(#function) return true } func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool { print(#function) return true } //... } } Or you may try subclassing NSTextField and override methods like textShouldBeginEditing(_:), textDidBeginEditing(_:), textDidChange(_:) ... in the subclass.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Jul ’21
Reply to View does not update
Thanks for showing your code. As far as I checked your code, the most critical parts in your code were: PlayerView(Color("C1"), player: mainViewModel.player1) //... PlayerView(Color("C2"), player: mainViewModel.player2) As you may already know, the parameter player: is of type PlayerModel, which is a struct -- a value type. Meaning the value is copied on assignment. This sort of duplication may cause some unexpected behaviors in SwiftUI. One possible solution would be using Binding: MainView struct MainView: View { //...     var body: some View { //... //P1 PlayerView(Color("C1"), player: $mainViewModel.player1) //<- .padding(15) //settings&info midSection //P2 PlayerView(Color("C2"), player: $mainViewModel.player2) //<- .padding(15) //... } } PlayerView struct PlayerView: View { //... @Binding var player: PlayerModel //<- init(_ playerBackgroundColor: Color, player: Binding<PlayerModel>) { self.playerBackgroundColor = playerBackgroundColor self._player = player //<- } //... } Please try.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Jul ’21
Reply to Char comparison not working
Sorry, but it's far from clarifying what is the problem of your current code. When you will successfully added info about what is the problem, I would write some replies. What is the expected result? And what is the actual result?
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Jul ’21
Reply to Failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project
The error Failed to produce diagnostic for expression is one of the big flaws in the current implementation of SwiftUI and Swift compiler. It just is indicating that there is some sort of errors in the block which is a very little clue for us developers. You may need find where is the part causing the issue by splitting your code by commenting out some parts one by one. For example, the following compiles successfully: struct GameView: View { @State var score = 0 @State private var playerWord = "" @State private var usedwords = [String]() var body: some View { ZStack{ LinearGradient(gradient: Gradient(colors: [Color.red, Color.orange]), startPoint: .top, endPoint: .bottom) .edgesIgnoringSafeArea(.vertical) VStack{ HStack{ Image("chain").scaleEffect(1.3) Image("chain").scaleEffect(1.3).rotationEffect(Angle(degrees: 90)) Image("chain").scaleEffect(1.3) Image("chain").scaleEffect(1.3).rotationEffect(Angle(degrees: 90)) Image("chain").scaleEffect(1.3) } HStack{ Text("Score:") Text(String(score)) }.padding() Spacer() Spacer() VStack { /* TextField("Enter a Word", text: $playerWord, onCommit: addNewWord()->Void) .padding() .border(Color.black, width: 2) .scaleEffect(0.8) */ List(usedwords, id: \.self){ Text($0) } } Spacer() HStack{ Image("chain").scaleEffect(1.3).rotationEffect(Angle(degrees: 90)) Image("chain").scaleEffect(1.3) Image("chain").scaleEffect(1.3).rotationEffect(Angle(degrees: 90)) Image("chain").scaleEffect(1.3) Image("chain").scaleEffect(1.3).rotationEffect(Angle(degrees: 90)) } } } } func addNewWord(){ let answer = playerWord.lowercased().trimmingCharacters(in: .whitespacesAndNewlines) guard answer.count > 0 else { return } usedwords.insert(answer, at: 0) playerWord = "" } } With examining the code commented out carefully, it seems the parameter passed to onCommit: is invalid in Swift. It should be: TextField("Enter a Word", text: $playerWord, onCommit: addNewWord) //<- No `()->Void` here .padding() .border(Color.black, width: 2) .scaleEffect(0.8)
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Jul ’21