5个随机Swift片段

  1. 使FileManager使用URL和路径
 扩展FileManager 
{
func fileExists(URL:URL)->布尔
{
返回self.fileExists(atPath:url.path)
}
  func removeFileIfExistsAtURL(_ url:Foundation.URL)抛出 
{
保护fileExists(at:url)else {return}
尝试removeItem(atPath:url.path)
}
}

我知道它愚蠢的简单,并且有一个很好的论据将它们仅保留为路径(更好的是将其作为适当的“文件路径”类型),但是为了方便起见,这非常方便,特别是因为许多其他框架仅返回URL。

2.平等

 扩展FloatingPoint 
{
func equal(to value:Self,精度为Self)-> Bool
{
令lhs =(自我/准确性).rounded()*准确性
令rhs =(toValue /准确度).rounded()*准确度
 返回lhs == rhs 
}
}

在很多情况下,例如在处理纬度/经度时,您仅在意一个值是否等于N个小数点。

3.对

 扩展数组 
{
func pair()-> [((Element,Element)]
{
返回Array (zip(self,self.dropFirst()))
}
}
  //示例: 
 令tmp = [1,2,2,3,1] 
让结果= tmp.pairs()
  //结果== [(1,2 ,,(2,2),(2,3),(3,1)] 
  //或如何: 
 令tmp = [CGPoint(x:10,y:20), 
CGPoint(x:100,y:30),
CGPoint(x:30,y:50),
CGPoint(x:50,y:10)]
让结果= tmp.pairs()
  //结果== [(CGPoint(x:10,y:20),CGPoint(x:100,y:30)), 
(CGPoint(x:100,y:30),CGPoint(x:30,y:50)),
(CGPoint(x:30,y:50),CGPoint(x:50,y:10))]

给定一系列元素,将它们配对。 第二个示例配对CGPoint也许是为了获得它们之间的距离。

4.蓄能器

扩展数组,其中元素: Numeric 
{
func accumulate()-> [Element]
{
返回self.enumerated()
.map {(索引,初始)在
self [0 .. <index] .reduce(initial,+)
}
}
}
  //示例:- 
 令tmp = [1,2,2,3,1] 
让结果= tmp.accumulate()
  //结果== [1,3,5,8,9] 

想象一下,您有一个点与点之间的距离列表,并且您想要到每个点的总距离……那就是这样做的! (也许与上述.pair()方法配对( 无双关)?)

5.交错

 扩展数组 
{
func paired(with array:[Element])-> [((Element,Element)]
{
返回Array (zip(self,array))
}
  func interleave(_ array:[Element])-> [Element] 
{
让交错= self.paired(with:数组)
.flatMap {[$ 0.0,$ 0.1]}
 让minCount = Swift.min(self.count,array.count) 
返回交错+ self [minCount ...] + array [minCount ...]
}
}
  //示例: 
 让数字= [“一个”,“两个”,“三个”,“四个”] 
让动物= [“牛”,“狗”]
 让结果= numbers.interleave(动物) 
  //结果== [“一个”,“牛”,“两个”,“狗”,“三个”,“四个”] 

最后一个从片段3的.pairs()方法的变体开始,该片段采用第二个数组,并与它和self配对。 请注意, zip函数会自动切片两个数组的长度以进行匹配。 然后在交织功能中,我们添加该zip操作切断的所有元素。