Swift:for循环,搜索字典,从键设置变量

时间:2016-06-18 21:23:52

标签: swift string dictionary

错误是:无法转换type(String:Int)的值?指定类型'String'。

显然,我的字典'roster'是'String:Int',函数'printRoster'中的局部变量('lastPlayer'和'firstPlayer')是String。但我已经尝试过每一个没有运气的变化。在我制作一个字典之前它工作得很好,它只是一个字符串。

它应该做什么:函数连接一个字符串,使其具有正确的标点符号。第一个字符串是“名单包含”,然后我们添加位于字典'名册'的键中的每个玩家。但是名单中的第一个键没有逗号,最后一个键得到',和'。

此外,我可以在协议中添加字典'名册',没有看到任何Apple手册中的语法

[R, Opt <: Option[R]]

4 个答案:

答案 0 :(得分:1)

这个怎么样:

let roster = ["Stephen Curry":1, "Andrew Bogu": 2, "Klay Thompson":3]

let players = roster.keys.joined(separator: ", ")
let all = "Roster contains: \(players)."

答案 1 :(得分:0)

鉴于此词典

let roster = ["Stephen Curry":1, "Andrew Bogu": 2, "Klay Thompson":3]

你可以

let elms = roster
    .keys
    .reduce("") { $0.1 + ", " + $0.0 }
    .characters
    .dropLast()
    .dropLast()

let res = "The roster includes " + String(elms)

<强>结果

"The roster includes Andrew Bogu, Stephen Curry, Klay Thompson"

更新#1:使用FOR LOOP

因为你想在这里使用for循环代码

let roster = ["Stephen Curry":1, "Andrew Bogu": 2, "Klay Thompson":3]
var result = "The roster includes "
for (index, elm) in roster.keys.enumerate() {
    result += elm
    if index < roster.keys.count - 1 {
        result += ", "
    }
}

print(result) // The roster includes Klay Thompson, Stephen Curry, Andrew Bogu

更新#2:使用第一个和最后一个的FOR LOOP

let roster = ["Stephen Curry":1, "Andrew Bogu": 2, "Klay Thompson":3]

func printRoster() -> String {

    var rosterPrint = "The roster includes"
    let players = Array(roster.keys)


    guard let
        first = players.first,
        last = players.last
        else { return "" } // this is ugly, it should return nil instead...

    for player in players {
        switch player {
        case first: rosterPrint += " \(player)"
        case last: rosterPrint += ", and \(player)."
        default: rosterPrint += ", \(player)"
        }
    }
    return rosterPrint
}

printRoster() // "The roster includes Klay Thompson, Stephen Curry, and Andrew Bogu."

答案 2 :(得分:0)

如果您仍想将“和”添加到最后一行,可以使用此功能:

func printRoster() -> String {
  var rosterPrint = "The roster includes"
  let arr = Array(roster.keys)
  let firstPlayer: String = arr.first!
  let lastPlayer: String = arr.last!
  for (player, _ ) in roster {
    switch player {
    case firstPlayer:
      rosterPrint += " \(player)"
    case lastPlayer:
      rosterPrint += ", and \(player)."
    default:
      rosterPrint += ", \(player)"
    }
   }
   return rosterPrint
}

并称之为:

print(goldenStateWarriors.printRoster())

答案 3 :(得分:0)

这似乎运作良好,至少在他们允许.first和.last使用词典之前(如果可能的话)。

    class BasketballTeam {
    var teamName: String?
    var numberOfPlayers: Int?
    var locatedIn: String?
    var roster = [String: Int]()

    init(teamName: String) {
        self.teamName = teamName
    }

    func printTeamLocation() -> String {
        return "The \(teamName) are located in \(locatedIn)"
    }
    func printRoster() -> String {
        var rosterPrint = "The roster includes"
        let rosterArray = Array(roster.keys)

        for player in rosterArray {

            let firstPlayer = rosterArray.first
            let lastPlayer = rosterArray.last

            switch player {
            case firstPlayer!:
                rosterPrint += " \(player)"
            case lastPlayer!:
                rosterPrint += ", and \(player)."
            default:
                rosterPrint += ", \(player)"
            }
        }
        return rosterPrint
    }
}

完整代码,如果您想学习快速熟悉篮球,可以粘贴到游乐场

import UIKit

protocol basketballTeams {
    var teamName: String { get }
    var numberOfPlayers: Int { get }
    var locatedIn: String { get }
    var roster: [String: Int] { get }

    func printTeamLocation()
}

class BasketballTeam {
    var teamName: String?
    var numberOfPlayers: Int?
    var locatedIn: String?
    var roster = [String: Int]()

    init(teamName: String) {
        self.teamName = teamName
    }

    func printTeamLocation() -> String {
        return "The \(teamName) are located in \(locatedIn)"
    }
    func printRoster() -> String {
        var rosterPrint = "The roster includes"
        let rosterArray = Array(roster.keys)

        for player in rosterArray {

            let firstPlayer = rosterArray.first
            let lastPlayer = rosterArray.last

            switch player {
            case firstPlayer!:
                rosterPrint += " \(player)"
            case lastPlayer!:
                rosterPrint += ", and \(player)."
            default:
                rosterPrint += ", \(player)"
            }
        }
        return rosterPrint
    }
}

enum NumberedPosition: Int {
    case PointGuard = 1
    case ShootingGuard, SmallForward, PowerForward, Center
    func labelOfPosition() -> String {
        switch self {
        case .PointGuard:
            return "Point Guard"
        case .ShootingGuard:
            return "Shooting Guard"
        case .SmallForward:
            return "Small Forward"
        case .PowerForward:
            return "Power Forward"
        case .Center:
            return "Center"
        default:
            "Position doesn't exist"
        }
    }
}

let goldenStateWarriors = BasketballTeam(teamName: "Golden State Warriors")
goldenStateWarriors.numberOfPlayers = 12
goldenStateWarriors.locatedIn = "Oakland, California"
goldenStateWarriors.roster = ["Stephen Curry" : 1, "Andrew Bogut" : 5, "Klay Thompson" : 2]
goldenStateWarriors.roster["Harrison Barnes"] = 3

goldenStateWarriors.printRoster()
goldenStateWarriors.printTeamLocation()

var num = 3

if let numberToPositionConv = NumberedPosition(rawValue: num) {
    let description = numberToPositionConv.labelOfPosition()
}