Swift3 - String 字符串、Array 数组、Dictionary 字典的使用
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 字典的使用的更多相关文章
- [Swift通天遁地]五、高级扩展-(6)对基本类型:Int、String、Array、Dictionary、Date的扩展
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...
- swift2.0 字符串,数组,字典学习代码
swift 2.0 改变了一些地方,让swift变得更加完善,这里是一些最基本的初学者的代码,里面涉及到swift学习的最基本的字符串,数组,字典和相关的操作.好了直接看代码吧. class View ...
- string字符串转数组
/** * THis_is_a_cat * This Is A Cat * * Cat A Is This * @author Administrator * */ public class Test ...
- Swift - 1 (常量、变量、字符串、数组、字典、元组、循环、枚举、函数)
Swift 中导入类库使用import,不再使用<>,导入自定义不再使用"" import Foundation 1> 声明变量和常量 在Swift中使用 &qu ...
- swift学习之label,button,imageView,字符串,数组,字典
import UIKit class ViewController: UIViewController,UITextFieldDelegate { var textField: UITextField ...
- Swift 3.0 字符串、数组、字典的使用
1.字符串 string func stringTest() -> Void { // 字符串 let str1 = "yiyi" let str2 = "2222 ...
- Swift学习字符串、数组、字典
一.字符串的使用 let wiseWords = "\"I am a handsome\"-boy" var emptyString = "" ...
- 字符串转数组(php版)
思路: 1.判断当前传来的值是否为数组 2.若不是现将传来的值转换为字符串类型 3.判断当前值是否为空 4.若不为空,采用正则进行匹配,如下图 preg_match('/^{.*?}$/', $str ...
- 03- Shell脚本学习--字符串和数组
字符串 字符串是shell编程中最常用最有用的数据类型(除了数字和字符串,也没啥其它类型好用了),字符串可以用单引号,也可以用双引号,也可以不用引号.单双引号的区别跟PHP类似: 单双引号的区别: 双 ...
随机推荐
- 让ASP.NET5在Jexus上飞呀飞
就在最近一段时间,“Visual Studio 2015 CTP 5”(以下简称CTP5)发布了,CTP5的发布不仅标志着新一代的VisualStudio正式发布又向前迈出了一步,还标志着距离ASP. ...
- ASP.NET MVC Model验证(一)
ASP.NET MVC Model验证(一) 前言 前面对于Model绑定部分作了大概的介绍,从这章开始就进入Model验证部分了,这个实际上是一个系列的Model的绑定往往都是伴随着验证的.也会在后 ...
- 在PC上测试移动端网站和模拟手机浏览器的5大方
查了很多资料,尝试了大部分方法,下面将这一天的努力总结下分享给大家,也让大家免去看那么多文章,以下介绍的方法,都是本人亲自测试成功的方法,测试环境winxp. 一.Chrome*浏览器 chrome模 ...
- 解析大型.NET ERP系统 业务逻辑设计与实现
根据近几年的制造业软件开发经验,以我开发人员的理解角度,简要说明功能(Feature)是如何设计与实现的,供参考. 因架构的不同,技术实现上会有所差异,我的经验仅限定于Windows Form程序. ...
- webpack入门之简单例子跑起来
webpack介绍 Webpack是当下最热门的前端资源模块化管理和打包工具,它可以将很多松散的模块按照依赖和规则打包成符合生产环境部署的前端资源,还可以将按需加载的模块进行代码分割,等到实际需要的时 ...
- ASP.NET OAuth:access token的加密解密,client secret与refresh token的生成
在 ASP.NET OWIN OAuth(Microsoft.Owin.Security.OAuth)中,access token 的默认加密方法是: 1) System.Security.Crypt ...
- YYModel 源码解读 总结
在使用swfit写代码的过程中,使用了下oc写的字典转模型,发现有些属性转不成功,就萌生了阅读源码的想法. 其实一直都知道Runtime机制,但并没有系统的学习,可能是因为平时的使用比较少,无意间在g ...
- 由objC运行时所想到的。。。
objC语言不仅仅有着面向对象的特点(封装,继承和多态),也拥有类似脚本语言的灵活(运行时),这让objC有着很多奇特的功能-可在运行时添加给类或对象添加方法,甚至可以添加类方法,甚至可以动态创建类. ...
- ARM CPU大小端
ARM CPU大小端: 大端模式:低位字节存在高地址上,高位字节存在低地址上 小端模式:高位字节存在高地址上,低位字节存在低地址上 STM32属于小端模式,简单的说,比如u32 temp=0X1234 ...
- Discuz X3.2 网站快照被劫持的解决方法
附上另一个人的解决方法:http://www.discuz.net/thread-3549930-3-1.html 问题如下: 快照被劫持,无论怎么申诉,怎么更新快照,都无法消除此问题,第一次打开网站 ...