【问题标题】:facing Unexpected non-void return value in void function in swift [duplicate]在swift中的void函数中面对意外的非void返回值[重复]
【发布时间】:2018-07-10 11:04:32
【问题描述】:

我收到“swift 中的 void 函数中出现意外的非 void 返回值”的错误。以及如何调用这个函数。我想要返回字符串并希望将其作为参数传递。请看我下面的代码

static func truetime() -> String? {

        let client = TrueTimeClient.sharedInstance
        //client.start()
        client.fetchIfNeeded { result in
            switch result {
            case let .success(referenceTime):
                let now = referenceTime.now()
                //print("Time is " + "\(now)")
                let dateFormatter : DateFormatter = DateFormatter()
                dateFormatter.dateFormat = "\(KeyValues.datetimeformat)"
                dateFormatter.timeZone = TimeZone(abbreviation: "GMT+05:00")
                let dateString = dateFormatter.string(from: now)

                print("Time is " + "\(dateString)")
                return dateString
            case let .failure(error):
                print("Error! \(error)")
            }
        }

    }

【问题讨论】:

  • client.fetchIfNeeded { result in … } 是一个具有 void 返回类型的闭包(类似于内联函数)。 return dateString 正在尝试返回不允许的 String

标签: ios swift switch-statement


【解决方案1】:

这个

return dateString

内部完成 void return 出现故障,您需要对异步任务使用完成

//

static func truetime(completion:@escaping(_ dateString:String?) -> Void ){

    let client = TrueTimeClient.sharedInstance
    //client.start()
    client.fetchIfNeeded { result in
        switch result {
        case let .success(referenceTime):
            let now = referenceTime.now()
            //print("Time is " + "\(now)")
            let dateFormatter : DateFormatter = DateFormatter()
            dateFormatter.dateFormat = "\(KeyValues.datetimeformat)"
            dateFormatter.timeZone = TimeZone(abbreviation: "GMT+05:00")
            let dateString = dateFormatter.string(from: now)

            print("Time is " + "\(dateString)")
            completion(dateString)
        case let .failure(error):
            print("Error! \(error)")
            completion(nil)
        }
    }

}

这样使用

className.truetime { (dateString) in

   if let date = dateString {


   }
}

【讨论】:

  • 请使用我的代码向我发送代码
  • 查看编辑......
  • 我想在这个语句中使用返回值作为参数 let parameters = [ "breakin_time": " ", "user_id": "(data)","company_id": "(data1)" , "in_break" : 1 ] as [String : Any]
猜你喜欢
  • 2023-03-09
  • 2021-06-27
  • 1970-01-01
  • 1970-01-01
  • 2015-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多