Where to put reusable functions in IOS Swift?

前端 未结 5 892
[愿得一人]
[愿得一人] 2020-12-13 03:53

New to IOS programming but just wondering where is the best place to put functions that I would use throughout my code. For example, I want to write a few functions to perfo

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 04:13

    For reusable functions it depends what I decide to use. For this specific case I use a separate file, because posting to a backend will become more complicated when the application evolves. In my app I use a backend class, with all kinds of helper classes:

    struct BackendError {
        var message : String
    }
    
    struct SuccessCall {
        var json : JSON
    
        var containsError : Bool {
            if let error = json["error"].string {
                return true
            }
            else {
                return false
            }
    
        }
    }
    
    typealias FailureBlock  = (BackendError) -> Void
    typealias SuccessBlock  = (SuccessCall) -> Void
    
    typealias AlamoFireRequest = (path: String, method: Alamofire.Method, data: [String:String]) -> Request
    typealias GetFunction = (path: String , data: [String : String], failureBlock: FailureBlock, successBlock: SuccessBlock) -> Void
    
    class Backend {
       func getRequestToBackend (token: String )(path: String , data: [String : String], failureBlock: FailureBlock, successBlock: 
    
    }
    

    For other cases I often use extensions on Swift classes. Like for getting a random element from an Array.

    extension Array {
        func sampleItem() -> T {
            let index = Int(arc4random_uniform(UInt32(self.count)))
            return self[index]
        }
    }
    

提交回复
热议问题