Swift2中的String与Character

前端之家收集整理的这篇文章主要介绍了Swift2中的String与Character前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

从Swift2开始,String不再遵守CollectionType协议,即不再是集合类型,但是String的属性characters遵守CollectionType协议。

String的characters属性的类型是CharacterView(结构体)

获取字符串String中单独的字符Character:

for character in "Dog".characters {
    print(character)
}

使用Character类型的数组构造字符串String:

let catCharacters: [Character] = ["C","a","t","!"]
let catString = String(catCharacters)

将字符串String转化为字符数组[Character]:

let string: String = "abcdefg"
var characters = [Character]()
for character in string.characters {
    characters.append(character)
}

猜你在找的Swift相关文章