我是新來的Swift(我在一個月前瞭解它),我創建了一個自定義的UICollectionViewCell類,並且我還需要三種類型的UIButtons和其他對象,但我不想寫每一個,所以我正在創建一個函數。但是,由於我有三個按鈕,函數必須爲每個參數準確地使用三個數組。有人可以幫我解釋一下包含評論的代碼嗎?謝謝!如何檢查作爲UDF參數的數組中的值的數量?
var buttonArray: [UIButton] = []
var checkBoxArray: [UIView] = []
var labelArray: [UILabel] = []
func initializeStuff(objectType: AnyObject, xOriginCgFloat: [CGFloat], yOriginCgFloat: [CGFloat], width: [CGFloat], height: [CGFloat]) {
if xOriginCgFloat != Array() || yOriginCgFloat != Array() || width != Array() || height != Array() {
fatalError("Each CgFloat parameter must be an array.")
} else {
if AnyObject.self == UIButton.self {
if condition { //condition: each array must contain exactly three values
for index in 0..<3 {
var button = UIButton(frame: CGRect.init(origin: CGPoint.init(x: xOriginCgFloat[index], y: yOriginCgFloat[index]), size: CGSize.init(width: width[index], height: height[index])))
buttonArray.append(button)
}
} else {
fatalError("Each array for a button object must have exactly three values.")
}
} else if AnyObject.self == UIView.self {
if condition2 { //condition2: each array must contain exactly two values
for index in 0..<2 {
var checkBox = UIView(frame: CGRect.init(origin: CGPoint.init(x: xOriginCgFloat[index], y: yOriginCgFloat[index]), size: CGSize.init(width: width[index], height: height[index])))
checkBoxArray.append(checkBox)
}
} else {
fatalError("Each array for a view object must have exactly two values.")
}
} else if AnyObject.self == UILabel.self {
if condition3 { //condition3: each array must contain exactly two values
for index in 0..<2 {
var label = UILabel(frame: CGRect.init(origin: CGPoint.init(x: xOriginCgFloat[index], y: yOriginCgFloat[index]), size: CGSize.init(width: width[index], height: height[index])))
labelArray.append(label)
}
} else {
fatalError("Each array for a view object must have exactly two values.")
}
} else {
fatalError("Incorrect type of object; AnyObject parameter must be a UIButton, UIView, or UILabel.")
}
}
}
當你說'if objectType == UIButton.self {'應該將等號運算符改爲身份運算符(===),因爲Xcode給我一個錯誤信息==。另外,因爲我想爲UIButton調用三個值,並且有兩個值UIView和UILabel,有沒有辦法讓一個元組具有不同數量的值? – ProgrammingEnthusiast
如何在我的'for'循環中得到元組中三個值中的一個?我也發佈了另一個問題。 – ProgrammingEnthusiast
@ProgrammingEnthusiast是:'AnyObject'不是'Equatable',所以我應該使用'==='比較身份而不是'=='。對於那個很抱歉。另外,使用for循環遍歷一個元組並不是真的支持。這是可能的,但很混亂。所以如果你想使用for循環方法,那麼元組可能不是一個很好的解決方案,你應該堅持使用數組。對不起,不好的建議。 – Robert