将 if ((loc = [player locateCardValue:8]) > - 1) 转换为 Swift 3
Convert if ((loc = [player locateCardValue:8]) > - 1) to Swift 3
你会如何转换这个Objective-C
if ((loc = [player locateCardValue:8]) > -1) {
到Swift 3?
[player locateCardValue]
returns 卡片 '8'
被发现位置的整数。返回 -1
表示没有找到卡片 '8'
.
我可以使用...
let loc = player.locateCard(withValue: 8)
if loc > -1 {
但我有多个 IF 嵌套,它会变得非常混乱。
也许最好的方法不是转换它 "as is",而是让它更 Swift-like。
在这种情况下,我想我会在找不到卡时将 locateCard
更改为 return 和 Optional<Int>
以及 return nil
。
func locateCard(withValue: Int) -> Card? {
// return the position if found, nil otherwise
}
那你就写
if let card = player.locateCard(withValue: 8) {
}
您最好的选择是将 locateCardValue
转换为 return 可选 Int?
。那么你可以简单地做
if let loc = player.locateCard(withValue: 8) {
// ...
}
或者您可以使用 switch 语句
switch player.locateCard(withValue: 8) {
case -1: print("No card.")
case 1: // ...
// etc.
}
你会如何转换这个Objective-C
if ((loc = [player locateCardValue:8]) > -1) {
到Swift 3?
[player locateCardValue]
returns 卡片 '8'
被发现位置的整数。返回 -1
表示没有找到卡片 '8'
.
我可以使用...
let loc = player.locateCard(withValue: 8)
if loc > -1 {
但我有多个 IF 嵌套,它会变得非常混乱。
也许最好的方法不是转换它 "as is",而是让它更 Swift-like。
在这种情况下,我想我会在找不到卡时将 locateCard
更改为 return 和 Optional<Int>
以及 return nil
。
func locateCard(withValue: Int) -> Card? {
// return the position if found, nil otherwise
}
那你就写
if let card = player.locateCard(withValue: 8) {
}
您最好的选择是将 locateCardValue
转换为 return 可选 Int?
。那么你可以简单地做
if let loc = player.locateCard(withValue: 8) {
// ...
}
或者您可以使用 switch 语句
switch player.locateCard(withValue: 8) {
case -1: print("No card.")
case 1: // ...
// etc.
}