简体   繁体   English

根据Swift中的参数返回不同类型的数据

[英]Returning different types of data depending on parameter in Swift

I have different clases, each one has their methods that return different types. 我有不同的分类,每个分类都有其返回不同类型的方法。 I don't want to repeat myself writing the same thing over and over again - feels like a bad practice, and I want to know if is possible with one function return the objects depending on the parameter given in the function. 我不想一遍又一遍地重复写同一件事-感觉像是一种不好的做法,我想知道一个函数是否可以根据函数中给定的参数返回对象。 As an example: 举个例子:

func myFunction(type: String) -> ?? {
   switch type {
       case myClass1:
           return objectTypeMyClass1
           break;
       case myClass2:
           return objectTypeMyClass2
           break;
       case myClass3:
           return objectTypeMyClass3
           break;
       default: 
           break;
   }
}

Is that a good practice? 这是个好习惯吗? It is possible. 有可能的。

You can use enum as a container for a type (something similar to how Apple have done optionals): 您可以将enum用作类型的容器(类似于Apple进行可选操作的方式):

enum TypeContainer {
    case SomeInt(Int)
    case SomeString(String)
    case SomeBool(Bool)

    init(int: Int) {
        self = .SomeInt(int)
    }

    init(string: String) {
        self = .SomeString(string)
    }

    init(bool: Bool) {
        self = .SomeBool(bool)
    }
}

let a = TypeContainer(string: "123")
let b = TypeContainer(int: 88)
let c = TypeContainer(bool: true)

switch a {
case .SomeInt(let i):
    println(i)
case .SomeString(let s):
    println(s)
case .SomeBool(let b):
    println(b)
default:
    break
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM