반응형
Swift에서 "Index"를 "Int"유형으로 변환하는 방법은 무엇입니까?
문자열에 포함 된 문자의 인덱스를 정수 값으로 변환하고 싶습니다. 헤더 파일을 읽으려고 시도했지만에 대한 유형을 찾을 수 없지만 메서드 (예 Index
:)가있는 프로토콜을 준수하는 것으로 보입니다 .ForwardIndexType
distanceTo
var letters = "abcdefg"
let index = letters.characters.indexOf("c")!
// ERROR: Cannot invoke initializer for type 'Int' with an argument list of type '(String.CharacterView.Index)'
let intValue = Int(index) // I want the integer value of the index (e.g. 2)
도움을 주시면 감사하겠습니다.
편집 / 업데이트 :
Xcode 10.2.x • Swift 5 이상
extension Collection where Element: Equatable {
func indexDistance(of element: Element) -> Int? {
guard let index = firstIndex(of: element) else { return nil }
return distance(from: startIndex, to: index)
}
}
extension StringProtocol {
func indexDistance(of string: Self) -> Int? {
guard let index = range(of: string)?.lowerBound else { return nil }
return distance(from: startIndex, to: index)
}
}
Xcode 9 • Swift 4
let letters = "abcdefg"
if let index = letters.index(of: "c") {
let distance = letters.distance(from: letters.startIndex, to: index)
print("distance:", distance)
}
if let index = letters.range(of: "cde")?.lowerBound {
let distance = letters.distance(from: letters.startIndex, to: index)
print("distance:", distance)
}
Collection의 인스턴스 메소드로 구현하려는 경우 :
extension Collection where Element: Equatable {
func indexDistance(of element: Element) -> Int? {
guard let index = index(of: element) else { return nil }
return distance(from: startIndex, to: index)
}
}
extension StringProtocol where Index == String.Index {
func indexDistance(of string: Self) -> Int? {
guard let index = range(of: string)?.lowerBound else { return nil }
return distance(from: startIndex, to: index)
}
}
놀이터 테스트
let letters = "abcdefg"
let char: Character = "c"
if let distance = letters.indexDistance(of: char) {
print("character \(char) was found at position #\(distance)") // "character c was found at position #2\n"
} else {
print("character \(char) was not found")
}
let cde = "cde"
if let distance = letters.indexDistance(of: cde) {
print("string \(cde) was found at position #\(distance)") // "string cde was found at position #2\n"
} else {
print("string \(string) was not found")
}
Xcode 8 • Swift 3
let letters = "abcdefg"
if let index = letters.characters.index(of: "c") {
let distance = letters.distance(from: letters.startIndex, to: index)
print("distance:", distance)
}
extension String {
func indexDistance(of character: Character) -> Int? {
guard let index = characters.index(of: character) else { return nil }
return distance(from: startIndex, to: index)
}
}
let letters = "abcdefg"
let char: Character = "c"
if let index = letters.indexDistance(of: char) {
print("character \(char) was found at position #\(index)") // "character c was found at position #2\n"
} else {
print("character \(char) was not found")
}
원래 답변
원래 문자열 시작 인덱스와 관련하여 distanceTo (index) 메서드를 사용해야합니다.
let intValue = letters.startIndex.distanceTo(index)
다음과 같이 문자열에서 첫 번째 문자를 반환하는 메서드를 사용하여 String을 확장 할 수도 있습니다.
extension String {
func indexDistanceOfFirst(character character: Character) -> Int? {
guard let index = characters.indexOf(character) else { return nil }
return startIndex.distanceTo(index)
}
}
let letters = "abcdefg"
let char: Character = "c"
if let index = letters.indexDistanceOfFirst(character: char) {
print("character \(char) was found at position #\(index)") // "character c was found at position #2\n"
} else {
print("character \(char) was not found")
}
스위프트 4
var str = "abcdefg"
let index = str.index(of: "c")?.encodedOffset // Result: 2
참고 : 문자열 에 동일한 여러 문자가 포함 된 경우 왼쪽에서 가장 가까운 문자 만 가져옵니다.
var str = "abcdefgc"
let index = str.index(of: "c")?.encodedOffset // Result: 2
참고URL : https://stackoverflow.com/questions/34540185/how-to-convert-index-to-type-int-in-swift
반응형
'developer tip' 카테고리의 다른 글
배낭 문제를 이해하는 방법은 NP 완전입니까? (0) | 2020.11.02 |
---|---|
스택 메모리 크기가 왜 그렇게 제한됩니까? (0) | 2020.11.02 |
C # FileStream : 대용량 파일을 쓰기위한 최적의 버퍼 크기? (0) | 2020.11.02 |
condition_variable.notify_one ()을 호출하기 전에 잠금을 획득해야합니까? (0) | 2020.11.02 |
MySQL IN 문의 PDO 바인딩 값 (0) | 2020.11.02 |