Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 根据Swift中的参数返回不同类型的数据_Ios_Macos_Swift - Fatal编程技术网

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

Ios 根据Swift中的参数返回不同类型的数据,ios,macos,swift,Ios,Macos,Swift,我有不同的类,每个类都有返回不同类型的方法。我不想重复一遍又一遍地写同样的东西——感觉这是一种糟糕的做法,我想知道是否可以使用一个函数根据函数中给定的参数返回对象。例如: func myFunction(type: String) -> ?? { switch type { case myClass1: return objectTypeMyClass1 break; case myClass2:

我有不同的类,每个类都有返回不同类型的方法。我不想重复一遍又一遍地写同样的东西——感觉这是一种糟糕的做法,我想知道是否可以使用一个函数根据函数中给定的参数返回对象。例如:

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

这是个好习惯吗?这是可能的。

您可以使用
enum
作为类型的容器(类似于Apple的optionals):


您可以尝试使用任何对象,但这是否是一种良好的做法?这取决于。。。苹果通常采用这种方法,例如在目标动作选择器中。你应该看看使用泛型类型,
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
}