例如:
var a = [1,2,3] // Ints var s = ",".join(a) // EXC_BAD_ACCESS
是否可以使加入函数返回“1,3”?
扩展Int(或其他自定义类型)以符合某些协议?
尝试这个
原文链接:https://www.f2er.com/swift/319582.htmlvar a = [1,".join(a.map { $0.description })
或添加此扩展
extension String { func join<S : SequenceType where S.Generator.Element : Printable>(elements: S) -> String { return self.join(map(elements){ $0.description }) } // use this if you don't want it constrain to Printable //func join<S : SequenceType>(elements: S) -> String { // return self.join(map(elements){ "\($0)" }) //} } var a = [1,".join(a) // works with new overload of join
连接被定义为
extension String { func join<S : SequenceType where String == String>(elements: S) -> String }
这意味着它需要一个字符串序列,你不能传递一个int序列.