【问题标题】:How to convert string to T in swift? [closed]如何快速将字符串转换为 T? [关闭]
【发布时间】:2018-08-17 07:03:58
【问题描述】:

我需要一个将字符串转换为泛型的方法:

到目前为止我已经尝试过了,但它不适用于 Int 对象。当我将对象作为 Int 传递给此方法时,它不会返回 Int 结果。你能帮我么。 一个例子;

let k : Int
gg(k,"testUrl") // Problem: this method call can't return int value.

func gg<T:Decodable>(_ nesne: T, _ URL: String) -> (T) {
   var returnValue : T?
   let data = "123" // <-- from web service
   returnValue = data as! T
   return returnValue
}

【问题讨论】:

  • (String(data: data!, encoding: .utf8)) 中的数据是什么?
  • 问题很明确。他创建了一个泛型函数,但它不适用于 int 对象......这意味着它无法在使用泛型函数返回时将字符串转换为 int。如果对此问题有任何解决方案或解释,您只需回答问题即可。这么粗鲁并不是必须的。
  • 问题很明确,c#中也存在类似问题:stackoverflow.com/questions/21807729/convert-string-to-t
  • @holex 问题与您的批评无关。与网络无关,与处理完成无关。问题显然是“为什么这个方法不返回 int 值”。您可以说“方法不会自动将字符串值转换为 int 值”或类似的话。你不是在这里招聘工人,也不是为你的学生考试。你正在努力帮助人们。
  • 即使你想批评人们编码,你也会让它变得“友好”。不是兽人风格...

标签: ios swift generics swift4


【解决方案1】:

我看不出如何在不定义解码器的情况下将字符串解码为泛型类型,因此要么需要一个实现 Decoder 的新类,要么为要使用的类型创建一个新协议有了这个功能。这是我使用协议的实现。

protocol EncodeFromString {
    associatedtype T
    func encodeFrom(_ str: String) -> T?
}

extension Int: EncodeFromString {
    typealias T = Int
    func encodeFrom(_ str: String) -> Int? {
        return Int(str)
    }
}

func gg<T: EncodeFromString>(_ nesne: T, _ URL: String) -> (T?) {
    let data = "123"
    return nesne.encodeFrom(data) as? T
}

【讨论】:

    【解决方案2】:

    一般情况下,String 类型并不总是能成功转换为其他类型,但您可以自行实现。

    示例

    class Functional<T> {
        var t: String
        var need: T {
            get {
                // you can support other types here
                if T.self == Int.self{
                    let re = Int(self.t)
                    return re as! T
                }
                fatalError()
            }
        }
        init(t_: String)  {
            t = t_
        }
    }
    let k : Int = 5
    func gg<T>(_ nesne: T, _ URL: String) -> (T) {
        let data = "123"
        let a = Functional<T>(t_: data)
        return a.need
    }
    print(gg(k, "hello"))
    

    【讨论】:

      猜你喜欢
      • 2015-06-19
      • 2019-07-20
      • 2014-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-09
      • 1970-01-01
      相关资源
      最近更新 更多