前端之家收集整理的这篇文章主要介绍了
Swift-字典,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
//
// main.swift
// DictonaryDemo
//
// Created by 程磊 on 15/5/20.
// Copyright (c) 2015年 chenglei. All rights reserved.
//
import Foundation
//字典的使用
let emptyDic1 = [:];//声明一个空的字典
let emptyDic2 = Dictionary<String,Float>();//声明一个空的字典,key为String类型,value为Float类型
var airports = ["TYO":"Tokyo","CN":"China","CD":"Canada"];
println(airports);
//添加修改
airports["USA"] = "American";//如果存在key则是修改,否则则是添加
println(airports);
//删除的方式有两种,1将字典中对应的value值设置nil,2.使用系统提供的方法,删除指定的value
airports["TYO"] = nil;
println(airports);
airports.removeValueForKey("USA");
println(airports);
//输出count
println("airports count is \(airports.count)");
println("airports count is " + String(airports.count));
//遍历字典
for (key,value) in airports {
println("key = \(key),value = \(value)");
}
//遍历所有的key
for key in airports.keys {
println("key = \(key)");
}
//遍历所有的value
for value in airports.values {
println("value = \(value)");
}
//将对应的values以及keys转化为数组
let allKeys = Array(airports.keys);
let allValues = Array(airports.values);
println(allKeys);
println(allValues);
原文链接:https://www.f2er.com/swift/327107.html