声明一个多类型数组

时间:2016-06-17 11:07:25

标签: ios arrays swift

我想让我的函数返回一个数组,其中第一个元素是String,第二个元素是UIImageView对象。 E.g。

["An example string", UIImageView()]

如何告诉函数将在 - >

后面的部分中返回该函数

所以基本上我想要一个像这样的函数:

func DoSomething(num:Int) -> Array[String, UIImageView()] {

    // Each of the following objects in the Array are UIImageView objects        
    Let imageViewObjects = [image1, image2, image3]

    return [String(num), imageViewObjects[num]]
}

但我知道我错了的部分是

Array[String, UIImageView]

P.S。我需要声明这个,因为如果我使用[AnyObject]它会在代码中引发错误,基本上说它不能操作AnyObject类型的对象

2 个答案:

答案 0 :(得分:4)

请注意,Array被声明为[Int]Array<Int>而不是Array[Int][Int]Array<Int>是一回事。你不需要同时使用它们。

最简单的方法是使用一个元组,声明如下:

(String, UIImageView)

我会像这样使用它(你的代码有更正):

import UIKit
typealias StringView = (String, UIImageView)
// Returning an Optional to pass back that num may be out of range
// note that I'm using the typealias StringView here
func DoSomething(num:Int) -> StringView? {
  let image1 = UIImageView()
  let image2 = UIImageView()
  let image3 = UIImageView()
  let imageViewObjects = [image1, image2, image3]
  // Need to check that num is a valid index
  guard num < imageViewObjects.count else { return nil }
  // return the tuple if num is valid
  return (String(num), imageViewObjects[num])
}

使用示例:

if let returned = DoSomething(2) {
  // printing the first item in returned tuple
  print(returned.0)
}

// output: "2"

您还可以使用协议创建通用协议,将其添加到扩展中的类,然后在声明中使用协议:

protocol Foo {}
extension String : Foo {}
extension UIImageView: Foo {}
var myArray:[Foo] ...

如果您要在很多地方使用返回的值,那么您可能希望将其变为成熟的structclass

import UIKit
struct StringView {
  let string:String
  let view:UIImageView
}

// Returning an Optional to pass back that num may be out of range
// note that I'm using the typealias StringView here
func DoSomething(num:Int) -> StringView? {
  let imageViewObjects = [UIImageView(),
                          UIImageView(),
                          UIImageView()]
  // Need to check that num is a valid index
  guard num < imageViewObjects.count else { return nil }
  // return the tuple if num is valid
  return StringView(string: String(num), view: imageViewObjects[num])
}

if let returned = DoSomething(2) {
  // printing the member "string" in the returned struct
  print(returned.string)
}

// output: "2"

除非使用自定义结构和类,否则元组通常是更好的选择。

答案 1 :(得分:1)

你可以在swift中使用Dictionary对象,在这里你可以使用key作为String,将值作为ImageView的数组

let imageViewObjects = [image1, image2, image3]
let array : [String : UIImageView] = [
    String(num) : imageViewObjects[num]
]

如果你想只返回数组,你可以这样做

let imageViewObjects = [image1, image2, image3]
var array : [AnyObject] = [AnyObject]()
array.append(String(num))
array.append(imageViewObjects[num])

在此,你必须确保第一个对象是String,第二个是UIImageView的数组

相关问题