let greenHex = hex.substring(with: Range<String.Index>(start: hex.index(hex.startIndex, offsetBy: 2), end: hex.index(hex.startIndex, offsetBy: 4)))
这是Swift3.0,hex是一个字符串,但是这段代码抛出一个错误说:
无法为类型&#39;范围&#39;调用初始化程序。与 类型&#39;的参数列表(start:String.Index,end:String.Index)&#39;
答案 0 :(得分:6)
Range.init(start:end:)
构造函数,因此您初始化如下的范围:
let range = hex.index(hex.startIndex, offsetBy: 2)..<hex.index(hex.startIndex, offsetBy: 4)
返回类型<String.Index>
的半开范围。然后,您可以执行以下操作:
hex.substring(with: range)