Swift3.0与Python一些默认函数的差异

Swift感觉吸取了很多语言的特性,因为原来用Python较多,所以很多用法和习惯其实都有,可能表现的函数名不同而已,这里把自己遇到的一些记录一下

切片

通过指定分隔符对字符串进行切片

Python:split
str = "a,b,c,d"
print (str.split(",")) 
# ['a', 'b', 'c', 'd']
Swift:components
var str = "a,b,c,d"
print (str.components(separatedBy: ","))
//['a', 'b', 'c', 'd']

//另外一种google到的复杂的写法
print(str.characters.split{$0 == ","}.map(String.init))

连接

连接字符串数组

Python:join
arr = ['a', 'b', 'c', 'd']
print (",".join(arr)) 
# "a,b,c,d"
Swift:joined
var arr = ["a", "b", "c", "d"]
print (arr.joined(separator: ","))
//"a,b,c,d"

//注意,Swift只有字符串才能被拼接,所以如果非字符串的数组需要先转换一下,例如
var arr = [1,2,3,"str"].map({num in return String(describing: num)})
print (arr.joined(separator: ","))


计数

数组计数

Python:len
arr = ['a', 'b', 'c', 'd']
print (len(arr)) 
# 4
Swift:count
var arr = ["a", "b", "c", "d"]
print (arr.count)
//4

数组

List和Set,数组去重复

Python:list,set
arr = ['a', 'a', 'b', 'b']
print (list(set(arr))) 
# ['a','b']
Swift:Array,Set
var arr = ["a", "a", "b", "b"]
print (Array(Set(arr)))
//["b", "a"]

排序

数组大小排序

Python:sorted
arr = [1,2,7,6,4]
print (sorted(arr)) 
#[1, 2, 4, 6, 7]
Swift:sorted
var arr = [1,2,7,6,4]
print (arr.sorted(by: <))
//[1, 2, 4, 6, 7]

替换

从字符串中替换部分字符

Python:replace
str = "Hello, playground"
print(str.replace("o","0"))
#'Hell0, playgr0und'
Swift:replacingOccurrences
var str = "Hello, playground"
print (str.replacingOccurrences(of: "o", with: "0"))
//"Hell0, playgr0und"

你可能感兴趣的:(Swift3.0与Python一些默认函数的差异)