Post

Replies

Boosts

Views

Activity

Reply to Async Sequence
As far as I read the proposal SE-0298Async/Await: Sequences, implementing AsyncSequence is far from intuitive. You may need to write something like this: func fetchAsyncImage(request: URLRequest) -> AsyncPhotos { return AsyncPhotos(request: request) } struct AsyncPhotos: AsyncSequence { typealias Element = UIImage let request: URLRequest struct AsyncIterator: AsyncIteratorProtocol { let request: URLRequest var photosIterator: Array<Photo>.Iterator? mutating func next() async throws -> UIImage? { if photosIterator == nil { let (data, response) = try await URLSession.shared.data(for: request) guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw FetchError.badRequest } let photos = try JSONDecoder().decode([Photo].self, from: data) photosIterator = photos.makeIterator() } guard let photo = photosIterator?.next() else { return nil } do { guard let imageURL = URL(string: photo.urlPath) else { throw FetchError.noURL } let (imageData, imageResponse) = try await URLSession.shared.data(from: imageURL) guard (imageResponse as? HTTPURLResponse)?.statusCode == 200 else { throw FetchError.invalidImageURL } guard let image = UIImage(data: imageData) else { throw FetchError.badImage } return image } catch { throw FetchError.invalidImageURL } } } func makeAsyncIterator() -> AsyncIterator { AsyncIterator(request: request) } } (Not tested. You may need to fix many parts.) I'm not sure if AsyncStream/AsyncThrowingStream can improve the way implementing AsyncSequence.
Topic: Programming Languages SubTopic: Swift Tags:
Jun ’21
Reply to Async Sequence
These things are not intuitive and i cant find good resources explaining them. Have you ever tried to make your custom type conform to Sequence? Making AsyncSequence is very similar to Sequence. And as explained in the session video you referred, Swift compiler compiles for-(try)-await as: var iterator = quakes.makeAsyncIterator() while let quake = await iterator.next() { //... } You need to implement what compiler demands. (typealias is a thing needed for making types conform to some protocol. Better read the Swift book carefully.)
Topic: Programming Languages SubTopic: Swift Tags:
Jul ’21
Reply to How to Handle NULL in Swift?
An interesting example. As you already know, a value that can be NULL would usually be imported into Swift as Optional and you use nil in Swift. But in the example you have referred, the Swift version of the function signature shows the return value as non-Optional: func CGColorSpaceCreateDeviceRGB() -> CGColorSpace Interestingly, the original C-declaration in CGColorSpace.h is marked with cg_nullable: /* Create a DeviceRGB color space. */ CG_EXTERN CGColorSpaceRef cg_nullable CGColorSpaceCreateDeviceRGB(void) CG_AVAILABLE_STARTING(10.0, 2.0); You can find some functions in CGColorSpace.h are marked with cg_nullable and imported as non-Optional in Swift, and some others marked with __nullable (which is a standard way to tell it is nullable to Swift importer) and imported as Optional. I'm not sure if this usage was intentional to distinguish nullable, but should be imported as Optional into Swift cases and simply nullable. But, in fact, when I use CGColorSpaceCreateDeviceRGB() in Swift, I do expect this would never return nil. When some functions may return NULL, but only in cases where continuing execution is not practical, such as Out of Memory, the imported type might be non-Optional in Swift. It would be better if this sort of mismatching was clearly documented. You can send a bug report using Apple's Feedback Assistant.
Topic: Programming Languages SubTopic: Swift Tags:
Jul ’21
Reply to How to load mp3 on Library Folder and play it.
Thanks for showing your code. The critical thing in your code is this part: do { let audioPlayer = try AVAudioPlayer(contentsOf: storedURL, fileTypeHint: AVFileType.mp3.rawValue) audioPlayer.play() print("sound is playing") } catch let error { print("Sound Play Error.lDescription -> \(error.localizedDescription)") print("Sound Play Error -> \(error)") } (As was shown in your first post, nice guess!) The problem is that the variable audioPlayer is local to the do-catch block. So, it will be lost immediately after print("sound is playing"). With audioPlayer.play(), playing the audio is just started but not finished. The instance of AVAudioPlayer needs to be held while playing. Please try something like this: struct ContentView: View { let playerManager = AudioPlayerManager.shared //<- @State var message: String = "Test Message2" @State var storedURL: URL? var body: some View { Text(message) .onTapGesture { guard let path = Bundle.main.path(forResource: "selectSE", ofType: "mp3") else { print("Sound file not found") return } let url = URL(fileURLWithPath: path) do { let fileData = try Data(contentsOf: url) storedURL = saveDataFile(data: fileData, fileName: "test.mp3", folderName: "testFolder") print("File Writing on View -> Success \(storedURL?.absoluteString ?? "nil") ") } catch { print("Data.init(contentsOf:) failed: \(error)") } playerManager.play(url: storedURL!) //<- print("end of code") } } //... } class AudioPlayerManager { static let shared = AudioPlayerManager() var audioPlayer: AVAudioPlayer? func play(url: URL) { do { audioPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue) //<- No `let` audioPlayer?.play() print("sound is playing") } catch let error { print("Sound Play Error -> \(error)") } } } You have no need to copy the sound file each time onTapGesture, but it is not critical and you may improve it later.
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
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 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 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 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 Async Sequence
As far as I read the proposal SE-0298Async/Await: Sequences, implementing AsyncSequence is far from intuitive. You may need to write something like this: func fetchAsyncImage(request: URLRequest) -> AsyncPhotos { return AsyncPhotos(request: request) } struct AsyncPhotos: AsyncSequence { typealias Element = UIImage let request: URLRequest struct AsyncIterator: AsyncIteratorProtocol { let request: URLRequest var photosIterator: Array<Photo>.Iterator? mutating func next() async throws -> UIImage? { if photosIterator == nil { let (data, response) = try await URLSession.shared.data(for: request) guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw FetchError.badRequest } let photos = try JSONDecoder().decode([Photo].self, from: data) photosIterator = photos.makeIterator() } guard let photo = photosIterator?.next() else { return nil } do { guard let imageURL = URL(string: photo.urlPath) else { throw FetchError.noURL } let (imageData, imageResponse) = try await URLSession.shared.data(from: imageURL) guard (imageResponse as? HTTPURLResponse)?.statusCode == 200 else { throw FetchError.invalidImageURL } guard let image = UIImage(data: imageData) else { throw FetchError.badImage } return image } catch { throw FetchError.invalidImageURL } } } func makeAsyncIterator() -> AsyncIterator { AsyncIterator(request: request) } } (Not tested. You may need to fix many parts.) I'm not sure if AsyncStream/AsyncThrowingStream can improve the way implementing AsyncSequence.
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Jun ’21
Reply to Cannot convert value of type 'ForgotPasswordEmailCheckController.Type' to expected argument type 'UIViewController'?
You need to pass an instance of UIViewController to pushViewController(_:animated:), not a type name:     navigationController?.pushViewController(forgotPasswordEmailCheck, animated: true)
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Jul ’21
Reply to Async Sequence
These things are not intuitive and i cant find good resources explaining them. Have you ever tried to make your custom type conform to Sequence? Making AsyncSequence is very similar to Sequence. And as explained in the session video you referred, Swift compiler compiles for-(try)-await as: var iterator = quakes.makeAsyncIterator() while let quake = await iterator.next() { //... } You need to implement what compiler demands. (typealias is a thing needed for making types conform to some protocol. Better read the Swift book carefully.)
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Jul ’21
Reply to Binding -> Return from initializer without initializing all stored properties
What video are you talking about? And please show enough code.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Jul ’21
Reply to How to Handle NULL in Swift?
An interesting example. As you already know, a value that can be NULL would usually be imported into Swift as Optional and you use nil in Swift. But in the example you have referred, the Swift version of the function signature shows the return value as non-Optional: func CGColorSpaceCreateDeviceRGB() -> CGColorSpace Interestingly, the original C-declaration in CGColorSpace.h is marked with cg_nullable: /* Create a DeviceRGB color space. */ CG_EXTERN CGColorSpaceRef cg_nullable CGColorSpaceCreateDeviceRGB(void) CG_AVAILABLE_STARTING(10.0, 2.0); You can find some functions in CGColorSpace.h are marked with cg_nullable and imported as non-Optional in Swift, and some others marked with __nullable (which is a standard way to tell it is nullable to Swift importer) and imported as Optional. I'm not sure if this usage was intentional to distinguish nullable, but should be imported as Optional into Swift cases and simply nullable. But, in fact, when I use CGColorSpaceCreateDeviceRGB() in Swift, I do expect this would never return nil. When some functions may return NULL, but only in cases where continuing execution is not practical, such as Out of Memory, the imported type might be non-Optional in Swift. It would be better if this sort of mismatching was clearly documented. You can send a bug report using Apple's Feedback Assistant.
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Jul ’21
Reply to How to load mp3 on Library Folder and play it.
What do you get when you change print(error.localizedDescription) to print(error)? (And please show enough code, using the Code Block feature.)
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Jul ’21
Reply to How to load mp3 on Library Folder and play it.
Thanks for showing your code. The critical thing in your code is this part: do { let audioPlayer = try AVAudioPlayer(contentsOf: storedURL, fileTypeHint: AVFileType.mp3.rawValue) audioPlayer.play() print("sound is playing") } catch let error { print("Sound Play Error.lDescription -> \(error.localizedDescription)") print("Sound Play Error -> \(error)") } (As was shown in your first post, nice guess!) The problem is that the variable audioPlayer is local to the do-catch block. So, it will be lost immediately after print("sound is playing"). With audioPlayer.play(), playing the audio is just started but not finished. The instance of AVAudioPlayer needs to be held while playing. Please try something like this: struct ContentView: View { let playerManager = AudioPlayerManager.shared //<- @State var message: String = "Test Message2" @State var storedURL: URL? var body: some View { Text(message) .onTapGesture { guard let path = Bundle.main.path(forResource: "selectSE", ofType: "mp3") else { print("Sound file not found") return } let url = URL(fileURLWithPath: path) do { let fileData = try Data(contentsOf: url) storedURL = saveDataFile(data: fileData, fileName: "test.mp3", folderName: "testFolder") print("File Writing on View -> Success \(storedURL?.absoluteString ?? "nil") ") } catch { print("Data.init(contentsOf:) failed: \(error)") } playerManager.play(url: storedURL!) //<- print("end of code") } } //... } class AudioPlayerManager { static let shared = AudioPlayerManager() var audioPlayer: AVAudioPlayer? func play(url: URL) { do { audioPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue) //<- No `let` audioPlayer?.play() print("sound is playing") } catch let error { print("Sound Play Error -> \(error)") } } } You have no need to copy the sound file each time onTapGesture, but it is not critical and you may improve it later.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Jul ’21
Reply to Error in Xcode 12.5.1: Unterminated string literal
Please show the whole source code where the error occurs.
Replies
Boosts
Views
Activity
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:
Replies
Boosts
Views
Activity
Jul ’21
Reply to Char comparison not working
Can you clarify what is the problem of your current code? What is the expected result? And what is the actual result?
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
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:
Replies
Boosts
Views
Activity
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:
Replies
Boosts
Views
Activity
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:
Replies
Boosts
Views
Activity
Jul ’21
Reply to FirebaseFirestoreSwift Packaging Firebase with SwiftUI
I do not want to go deep into Firestore, as it is not a framework of Apple's. But you may need to use addDocument(from:) instead of addDocument(data:). Better visit a supporting site or a community site of Firestore.
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
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:
Replies
Boosts
Views
Activity
Jul ’21