Swift从二维数组中获取字符串数组

时间:2019-12-11 23:16:26

标签: arrays swift string character 2d

这是我的代码:

var parentList = [String]()

for user in MPUser.array {
    if user.childParent == "parent" {
        parentList.append(user.firstName)
    }
}

guard parentList.contains((selectedSecondJob?.assigned)!) else {
    print("payday has to be a parent, yo!")
    return
}

它可以工作,但是我知道我可以通过使用诸如flatMap之类的高阶函数使其更加“迅速”。

这是我尝试过的:

let parentListTEST = MPUser.array.flatMap({ $0.childParent })

但是它返回一个字符数组,而不是字符串。为什么? MPUser数组是一个结构数组,可以清楚地将“ parent”参数定义为String而不是Character。

如何从我的MPUser数组中获得一个新数组,该数组的父对象名称为字符串而不是字符?

2 个答案:

答案 0 :(得分:1)

您可以尝试

this.props.handleChange(pets, true);  // handle changes
this.filterRooms(true);   // filtering with changing value

filterRooms = (pets) => {
  let {rooms} = this.props; 

  // filter by pets
  if (pets) {
    tempRooms = tempRooms.filter(room => room.pets === true);
  }

  this.props.filterRooms(tempRooms);
}

let parentListTEST = MPUser.array.filter { $0.childParent == "childParent" }.map { $0.firstName }

答案 1 :(得分:1)

使用mounted

public void handleAction (int x, int y) { if (gameOver) { JOptionPane.showMessageDialog (this, "Please Select Game...New to start a new game", "Game Over", JOptionPane.WARNING_MESSAGE); return; } int column = (x - BORDER_SIZE) / SQUARE_SIZE + 1; int row = findNextRow (board, column); if (row <= 0) { JOptionPane.showMessageDialog (this, "Please Select another Column", "Column is Full", JOptionPane.WARNING_MESSAGE); return; } animatePiece (currentPlayer, column, row); board [row] [column] = currentPlayer; int winner = checkForWinner (board, row, column); if (winner == BANANA) { gameOver = true; repaint (); backgroundMusic.stop(); winBanana.play(); JOptionPane.showMessageDialog (this, "Banana Wins!!!", "GAME OVER", JOptionPane.INFORMATION_MESSAGE); } else if (winner == STRAWBERRY) { gameOver = true; repaint (); backgroundMusic.stop(); winStrawberry.play(); JOptionPane.showMessageDialog (this, "Strawberry Wins!!!", "GAME OVER", JOptionPane.INFORMATION_MESSAGE); } else { currentPlayer *= -1; if (currentPlayer == 1) addStrawberry.play(); else addBanana.play(); } currentColumn = 3; repaint (); } 展平嵌套的集合。您正在映射map的列表,得到flatMap User(它们本身是childParent的集合)的数组,其中String是展平成单个数组。

您只希望映射不扁平化,因此只需使用Character