私有懒加载写法
private lazy var messageLabel: UILabel = {
let label = UILabel()
label.text = "关注一些人,回这里看看有什么惊喜"
label.textColor = UIColor.darkGrayColor()
label.font = UIFont.systemFontOfSize(14)
label.numberOfLines = 0
label.sizeToFit()
return label
}()
替换控制器的View
override func loadView() {
view = webView
}
// MARK: - 懒加载
private lazy var webView: UIWebView = {
let wv = UIWebView()
return wv
}()
swift中不存在隐式类型转换,但可以使用显示类型转换(强转)
var intValue:Int = 10
var doubleValue:Double
doubleValue = Double(intValue)
可选值
//有值的写法:
var optValue1: Int? = 9
//没有值的写法:
var optValue2: Int?
var optValue3: Int? = nil
//可选绑定
为了更安全的解析可选类型的值, 一般情况下使用可选绑定
如果optValue没有值就不会做任何操作, 如果optValue有值会返回true并将optValue的值赋值给result执行大括号中的内容
var optValue: Int? = 9
if let result3 = optValue
{
print(result3)
}
字符和字符串
//字符
var charValue1:Character = "a" //正确
var charValue1:Character = "ab" //错误写法,只能一个字符
//字符串
var stringValue1 = "ab"
//字符串常用方法
1.计算字符串长度
var stringValue = "abc李"
print(stringValue.characters.count);
2.字符串拼接
var str1 = "abc";
var str2 = "lnj";
var str = str1 + str2;
print(str)
3.字符串和其他数据类型的拼接
var index = 1
var str3 = "http://www.520it.com/pic/\(index).png"
4.字符串格式化
比如时间:12:03:04
let hour = 12
let min = 3
let second = 4
let time = String(format: "%02d:%02d:%02d", arguments: [hour,min, second])
5.字符串之间比较
var str4 = "abc";
var str5 = "abc";
if str4 == str5
{
print("相等");
}else
{
print("不相等");
}
6.字符串前缀和后缀判断
var str8 = "http://www.520it.com"
if str8.hasPrefix("http") {
print("是url");
}
if str8.hasSuffix(".com") {
print("是顶级域名");
}
7.字符串大小转换
var str9 = "abc.txt";
print(str9.uppercaseString)
print(str9.lowercaseString)
8.字符串截取
let hp = "Happy New Year"
var newHp = hp as NSString
let h = newHp.substringToIndex(5)
print(h) //打印出:Happy
数组
for i in 1...5 //包括5在内
{
print(i)
}
for i in 1..<5 //不包括5在内
{
print(i)
}
网友评论