Swift相关知识,本随笔为 字符串、数组、字典的简单使用。

///***********************************************************************************************************/

///  2016.12.29

///***********************************************************************************************************/

1、Swift3 ,字符串的简单使用,直接将代码贴过来,更方便查看

//  字符串 string
func stringTest() -> Void {
// 字符串
let str1 = "yiyi"
let str2 = ""
var str3 = String()//空string
var str4 = ""// 空string // 字符(字符为 一 个)
let char1:Character = "d" // 字符串长度
var strCount = str1.characters.count
strCount = str1.lengthOfBytes(using: String.Encoding.utf8)
print(String(format:"strCount == "),strCount) // 字符串转换integer
print((str2 as NSString).integerValue) // 字符串拼接
str3 = str1 + str2
// str3 = "\(str1)\(str2)"
// str3 = globalStr + String(str1)
print(String(format:"str3 == "),str3) // 字符串与字符拼接
// str4 = str1+String(char1)
str4 = "\(str1)\(char1)"
str4 = str1.appending(String(char1))// 其他类型转换string String() exp:String(strCount)
print(String(format:""),str4) //字符串与其他类型值的拼接
let int1 =
let int2 = 11.1
let str5 = String(format:"%i%.1f",int1,int2)
print(String(format:"str5 == "),str5) // 字符串枚举 遍历每个字符
let s1 = "hello world!"
if strCount != {
print("判断string长度不为0,不是空")
}
for c in s1.characters {
print(c)
} // 字符串比较
let ss1 = "hello"
let ss2 = ",banana"
var ss3 = ss1+ss2
if ss1 == ss2 {
print("ss1=ss2")
}
if ss1+ss2 == ss3 {
print("ss1+ss2=ss3")
}
if ss1 > ss2 {// h大于b
print("ss1>ss2")
}
// 判断字符串是否包含字符串
if (ss3 .range(of: ss1) != nil) {
print("字符串包含子串")
}
     if ss3.hasPrefix("he") {}
     if ss3.hasSuffix("a") {}
// 字符串 大小写
print(ss3.uppercased())// HELLO,BANANA
print(ss3.capitalized)// Hello,Banana
print(ss3.lowercased())// hello,banana
/*
// 这两个用法没 明白
print(ss3.uppercased(with: Locale(identifier: "l")))// HELLO,BANANA
print(ss3.lowercased(with: Locale(identifier: "o")))// hello,banana
*/ // 截取 修剪 字符串
print(ss3.substring(from: ss3.characters.index(of: ",")!))//,banana 截取字符串从“,”开始
print(ss3.substring(to: ss3.characters.index(of: ",")!))//hello 截取字符串到“,”结束
print(ss3.unicodeScalars[ss3.unicodeScalars.startIndex ..< ss3.unicodeScalars.index(of: ",")!]);// hello
print(ss3[ss3.index(ss3.startIndex, offsetBy: )])// o 取字符串的某个字符
ss3.remove(at: ss3.characters.index(of: ",")!)// 去除字符串中特殊字符
print(ss3)// hellobanana }

 2、数组的简单使用

// 数组 array
func arrayTest() -> Void {
// 初始化
// var array1:[Any] = []// 空 任意类型
// var array2 = Array<Any>()
// var array3:[String] = []// 空 string 类型
// var array4 = Array<String>()
// let array5 = Array<Any>(repeatElement("", count: 3))
var arr0 = ["what","test","swift","array"]
let arr1 = ["hyArr",,"hySwift",] as [Any]
var arr2 = [,"","swiftArr2",,,] as [Any]
print(arr2[], arr2[], separator: "* ") // arr0.count 数组count
print(String(format:"arr0 长度 == "),arr0.count)
// 判断数组是否为空
if arr1.isEmpty {
print("arr1数组是空")
}else {
print("arr1数组不空")
}
// arr1[arr1.count-2] 取数组的某个元素
print(arr1[arr1.count-])// hySwift
// print(arr1[0])// hyArr
// public var first: Self.Iterator.Element? { get }
print(arr1.first!)// hyArr // 遍历数组
for i in ..<arr1.count {
print(arr1[i])
}
// 包含
if arr0 .contains("test") {
print("数组包含 test")
}else {
print("数组不包含 test")
} // 删除元素
// arr2 .remove(at: 4)
// arr2 .removeSubrange(1..<3)// 删除 1、2 两个元素
// arr2 .removeLast()
// arr2 .removeFirst()
arr2 .removeAll()
print(arr2) // 添加元素
arr2 .append("new1")// ["new1"]
arr2.append(contentsOf: ["Shakia", "William"])
print(arr2)
arr2 = arr1 + arr2// ["hyArr", 1, "hySwift", 3, "new1"]
arr2 = arr1
arr2 .insert("insertElement", at: )//["hyArr", 1, "hySwift", "insertElement", 3, "new1"] // 更换
if let i = arr0.index(of: "test") {
arr0[i] = "测试"
}
arr2[] = "domy"
print(arr2) // 数组排序
var sortArr = [,,,,,]
sortArr.sort(by: >)
print(String(format:"排序后:"),sortArr)// 排序后: [8, 5, 3, 1, 0, 0] // 二维数组
let tArr1 = [["tSwift","haha"],,[,]] as [Any]
let subArr1 = tArr1[]
print(subArr1) /// Array => NSArray
/// 苹果的例子
/// Description:
/// The following example shows how you can bridge an `Array` instance to
/// `NSArray` to use the `write(to:atomically:)` method. In this example, the
/// `colors` array can be bridged to `NSArray` because its `String` elements
/// bridge to `NSString`. The compiler prevents bridging the `moreColors`
/// array, on the other hand, because its `Element` type is
/// `Optional<String>`, which does *not* bridge to a Foundation type.
let colors = ["periwinkle", "rose", "moss"]
let moreColors: [String?] = ["ochre", "pine"] let url = NSURL(fileURLWithPath: "names.plist")
(colors as NSArray).write(to: url as URL, atomically: true)
// true (moreColors as NSArray).write(to: url as URL, atomically: true)
// error: cannot convert value of type '[String?]' to type 'NSArray' /// Array 的更多其他用法点进去查看方法文档
}

3、字典的简单使用

    // 字典 dictionary
func dictionaryTest() -> Void {
// 创建字典
var dict = [:"ok",:"error"]// [key:value]
var emptyDict: [String: Any] = [:]// 空字典 var emptyDict: [Int: String] = [:]
emptyDict = ["key1":"value1","key2":] // Getting and Setting Dictionary Values
print(dict[]!)// ok
print(emptyDict["key1"]!)// value1
// 添加键值对
emptyDict["key3"] = "value3"
print(emptyDict)// ["key2": 2, "key3": "value3", "key1": "value1"]
// 更新键值对的value
emptyDict["key2"] = "updateValue2"
print(String(format:("更换value后:")),emptyDict) var interestingNumbers = ["primes": [, , , , , , ],
"triangular": [, , , , , , ],
"hexagonal": [, , , , , , ]]
// 排序
for key in interestingNumbers.keys {
interestingNumbers[key]?.sort(by: >)
}
print(interestingNumbers["primes"]!)
/// print(interestingNumbers)
/// ["hexagonal": [91, 66, 45, 28, 15, 6, 1],
/// "primes": [15, 13, 11, 7, 5, 3, 2],
/// "triangular": [28, 21, 15, 10, 6, 3, 1]] // 遍历字典
let imagePaths = ["star": "/glyphs/star.png",
"portrait": "/images/content/portrait.jpg",
"spacer": "/images/shared/spacer.gif"]
for (key, value) in imagePaths {
print("The path to '\(key)' is '\(value)'.")
} /// search a dictionary's contents for a particular value
// let glyphIndex = imagePaths.index {
// $0.value.hasPrefix("/glyphs")
// }
// print(imagePaths[glyphIndex!].value)// /glyphs/star.png
// print(imagePaths[glyphIndex!].key)// star
let glyphIndex = imagePaths.contains {
$.value.hasPrefix("/glyphx")
}
print(glyphIndex)// ture /// Bridging Between Dictionary and NSDictionary
// imagePaths as NSDictionary
print("keys:\((imagePaths as NSDictionary).allKeys) ,values:\((imagePaths as NSDictionary).allValues)") }

Swift3 - String 字符串、Array 数组、Dictionary 字典的使用的更多相关文章

  1. [Swift通天遁地]五、高级扩展-(6)对基本类型:Int、String、Array、Dictionary、Date的扩展

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  2. swift2.0 字符串,数组,字典学习代码

    swift 2.0 改变了一些地方,让swift变得更加完善,这里是一些最基本的初学者的代码,里面涉及到swift学习的最基本的字符串,数组,字典和相关的操作.好了直接看代码吧. class View ...

  3. string字符串转数组

    /** * THis_is_a_cat * This Is A Cat * * Cat A Is This * @author Administrator * */ public class Test ...

  4. Swift - 1 (常量、变量、字符串、数组、字典、元组、循环、枚举、函数)

    Swift 中导入类库使用import,不再使用<>,导入自定义不再使用"" import Foundation 1> 声明变量和常量 在Swift中使用 &qu ...

  5. swift学习之label,button,imageView,字符串,数组,字典

    import UIKit class ViewController: UIViewController,UITextFieldDelegate { var textField: UITextField ...

  6. Swift 3.0 字符串、数组、字典的使用

    1.字符串 string func stringTest() -> Void { // 字符串 let str1 = "yiyi" let str2 = "2222 ...

  7. Swift学习字符串、数组、字典

    一.字符串的使用 let wiseWords = "\"I am a handsome\"-boy" var emptyString = "" ...

  8. 字符串转数组(php版)

    思路: 1.判断当前传来的值是否为数组 2.若不是现将传来的值转换为字符串类型 3.判断当前值是否为空 4.若不为空,采用正则进行匹配,如下图 preg_match('/^{.*?}$/', $str ...

  9. 03- Shell脚本学习--字符串和数组

    字符串 字符串是shell编程中最常用最有用的数据类型(除了数字和字符串,也没啥其它类型好用了),字符串可以用单引号,也可以用双引号,也可以不用引号.单双引号的区别跟PHP类似: 单双引号的区别: 双 ...

随机推荐

  1. openfire的组件(Component)开发

    在之前的文章<Openfire阶段实践总结>中提到过一种openfire的扩展模式Compoent.本文将主要探讨对这种模式的应用与开发方法. 内部与外部组件介绍 在openfire中的许 ...

  2. XSS 前端防火墙 —— 无懈可击的钩子

    昨天尝试了一系列的可疑模块拦截试验,尽管最终的方案还存在着一些兼容性问题,但大体思路已经明确了: 静态模块:使用 MutationObserver 扫描. 动态模块:通过 API 钩子来拦截路径属性. ...

  3. Mono 4.0 Mac上运行asp.net mvc 5.2.3

    Mono 4.0 已经发布,二进制包已经准备好,具体的发布说明参见:http://www.mono-project.com/docs/about-mono/releases/4.0.0/. 今天在Ma ...

  4. 微信小程序首次官方分享的纪要

    先交代备注: 这次有关小程序的分享只有技术的 QA环节,其他如产品.入口.流量.与公众号的整合等等,回答都是暂时无法给出答案或不确定: 小程序最终发布时间官方也还未确定,不过说应该就是近期: 小程序的 ...

  5. [译]ZOOKEEPER RECIPES-Locks

    锁 全局式分布式锁要求任何时刻没有两个客户端会获得同一个锁对象,这可以通过使用ZooKeeper实现.像优先级队列一样,首先需要定义一个锁节点. 在ZooKepeer的发布中src/recipes/l ...

  6. ArtifactTransferException: Failure to transfer org.apache.openejb:javaee-api:jar:5.0-1

    最近在myeclipse上创建maven类型的web项目的时候,出现了一个错误. ArtifactTransferException: Failure to transfer org.apache.o ...

  7. 作为Coder的利器记载

    工作近三年,使用PC快六年,拥抱Mac整一年,投具器石榴裙三年.14年第一次被同事推荐Everything,开启了JeffJade对工具的折腾之旅,并乐此不疲.时去两年,这必然是消耗了一些时间,但对效 ...

  8. Atitti 载入类的几种方法    Class.forName ClassLoader.loadClass  直接new

    Atitti 载入类的几种方法    Class.forName ClassLoader.loadClass  直接new 1.1. 载入类的几种方法    Class.forName ClassLo ...

  9. .NET 程序集单元测试工具 SmokeTest 应用指南

    Smoke Test(冒烟测试),也称Regression Test(回归测试),是对软件的安装和基本功能的测试.一般地我们使用脚本来实现Smoke Test的自动化,可借用虚拟机的snapshot机 ...

  10. MongoDB下载安装与简单增删改查

    Windows下MongoDB的安装和配置.启动和停止 下载地址:MongoDB的官方下载网址是:https://www.mongodb.org/downloads 安装步骤1. 点击下载的mongo ...