如何比较Range <string.index>和DefaultBidirectionalIndices <string.characterview>?

时间:2016-09-16 14:06:19

标签: swift range swift3

这种比较适用于Swift 2,但在Swift 3中不再适用:

print("Hi") v_player1=input("Player 1, what is your name?\n") print("Cool, welcome "+v_player1\n) v_player2=input("Player 2, what is your name?\n") print("Awesome, hi "+v_player2\n) v_player1_pkmn=input(v_player1+" pick your pokemon"\n) from PIL import Image im = Image.open(v_player1_pkmn+'.jpg') im.show() v_player2_pkmn=input(v_player2+" pick your pokemon"\n) from PIL import Image im = Image.open(v_player2_pkmn+'.jpg') im.show() v_player1_hp=100 v_player2_hp=100 print("Ready to Battle?!") import pyaudio import wave CHUNK = 1024 wf = wave.open( 'battle.wav', 'rb') p = pyaudio.PyAudio() def callback(in_data, frame_count, time_info, flag): data= wf.readframes(frame_count) while (v_player1_hp > 0 and v_player2_hp > 0): v_player1_move = input(v_player1 + ",Select your move:(A)ttack (D)efend (P)otion") if v_player1_move.upper() == "A": v_player2_hp -= 10 elif v_player1_move.upper() == "D": v_player1_hp == 100 elif v_player1_move.upper() == "P": v_player1_hp += 5 else: print("not a valid move") v_player2_move = input(v_player2 + ",Select your move:(A)ttack (D)efend (P)otion") if v_player2_move.upper() == "A": v_player1_hp -= 10 elif v_player2_move.upper() == "D": v_player2_hp == 100 elif v_player2_move.upper() == "P": v_player2_hp += 5 else: print("not a valid move") print("Player1HP " + str(v_player1_hp)) print("Player2HP " + str(v_player2_hp)) else: if (v_player1_hp > v_player2_hp): print(v_player1 + " wins!") else: print(v_player2 + " wins!") return (data, pyaudio.paContinue) stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True, stream_callback=callback stream.start_stream() while stream.is_active(): time.sleep(0.1) stream.stop_stream() stream.close() wf.close() p.terminate()

如何比较Range和DefaultBidirectionalIndices?

2 个答案:

答案 0 :(得分:5)

来自SE-0065 – A New Model for Collections and Indices

  

在Swift 2中,collection.indices返回了一个Range<Index>,但由于范围是一对简单的索引而索引无法再自行推进,Range<Index>不再可迭代

     

为了保持上述代码的工作,Collection已经获得了一个始终可迭代的关联指数类型,......

由于rangeOfComposedCharacterSequence会返回范围 字符索引,解决方案是使用indices,但是 startIndex..<endIndex

myString.rangeOfComposedCharacterSequence(at: myString.startIndex) 
== myString.startIndex..<myString.endIndex

答案 1 :(得分:1)

据我所知,StringString.CharacterView没有简明的方法返回Range<String.Index>或类似的东西。

您可能需要使用范围运算符明确创建范围:

let myStringContainsOnlyOneCharacter = myString.rangeOfComposedCharacterSequence(at: myString.startIndex)
    == myString.startIndex..<myString.endIndex

或者仅比较上限,在您的情况下:

let onlyOne = myString.rangeOfComposedCharacterSequence(at: myString.startIndex).upperBound
    == myString.endIndex