美文网首页
Swift变量和区间的介绍

Swift变量和区间的介绍

作者: 农夫_三拳 | 来源:发表于2019-06-13 19:13 被阅读0次
//: Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"

/*

循环的介绍

常见的循环有:for/while/do while.

*/

for i in 10 ..< 50 {

print(i)

}

for i in 0...10 {  // 闭区间循环

print(i)

}

//  特殊写法    如果再for循环中不需要用到下标i

for _ in 0..<10{

print("hello")

}

/*8

while 和do while 循环

while 的判断句必须有真确的真假,没有非0即真

while 后面的()可以省略

*/

var a = 0

while a < 10 {

a += 1

}

/*

do while  的使用

使用repe关键字来代替了do

*/

var b = 0

repeat {

print(b)

b += 1

}while b<20

/*    Swift基本语法之字符串

首先我们来看下  oc 和Swift 中字符串的区别

在oc中字符串类型时 NSString 在 swift中字符串类型时String

oc中字符串@“”  Swift 中字符串 “”

*/

/*

使用 String 的原因

String 是一个结构体,性能更高

NSString 是一个 OC 对象,性能略差

String 支持直接遍历

Swift 提供了 String 和 NSString 之间的无缝转换

*/

//遍历字符串

var strr = "hello, Swift"

for c in strr.characters{

print(c)//  可以在控制台查看输出的结果

}

// 字符串的拼接

let str1 = "song"

let str2 = "xin"

let str3 = "zhe"

let str4 = str1+str2+str3

//  字符串和其他数据类型的拼接

let name = "宋新哲"

let age = 18

let info = "my name is\(name),age is\(age)"

//  字符串的格式化  比如时间:06:07

let min = 3

let second = 4

//let time = String(Formatter: "%02d:%02d",no_argument:[min,second])

let time = String(format: "%02d:%02d", arguments: [min, second])

/*

当然还有最常用的 字符串的截取

Swift中提供了特殊的截取方式

该方式非常麻烦

Index创建较为麻烦

简单的方式是将String转成NSString来使用

在标识符后加:as NSString即可

*/

let myStr = "www.baidu.com"

var subStr = (myStr as NSString).substring(from: 4)

subStr = (myStr as NSString).substring(from: 3)

//subStr =(myStr as NSString).substring(with: )

相关文章

网友评论

      本文标题:Swift变量和区间的介绍

      本文链接:https://www.haomeiwen.com/subject/kmdefctx.html