如果我有一个与此类似的字符串(存储在firebase中):
"[brown, black, blue, pink]"
如何将其转换为swift [brown, black, blue, pink]
答案 0 :(得分:0)
您可以使用using UnityEngine;
using System.Collections;
public class MusicPlayer : MonoBehaviour {
static MusicPlayer instance = null;
void Awake(){
if (instance != null){
Destroy(gameObject);
Debug.Log("Duplicate MusicPlayer Destroyed");
}
else{
instance = this;
GameObject.DontDestroyOnLoad(gameObject);
Debug.Log("Original MusicPlayer Created!");
}
}
}
功能分隔阵列的各个元素。然后,您可以使用using UnityEngine;
using System.Collections;
public class MusicPlayer : MonoBehaviour {
public static gameobject instance = null;
void Awake(){
if (instance != null){
Destroy(gameObject);
Debug.Log("Duplicate MusicPlayer Destroyed");
}
else{
instance = this;
GameObject.DontDestroyOnLoad(gameObject);
Debug.Log("Original MusicPlayer Created!");
}
}
}
从第一个字符串中删除第一个字符(“[”),使用let components = yourString.components(separatedBy: ", ")
删除最后一个元素的最后一个字符。
如果您使用的是Swift 4,则可以使用components[0].remove(at: components[0].startIndex)
和components[components.count - 1].substring(to: components[components.count - 1].index(before: components[components.count - 1].endIndex))
。
但正如rmaddy所说,你应该考虑以更好的方式存储你的数据(使用JSON或类似的东西),因为有人可以输入“hello,world”,这将使用这种方法分成两个组件。
答案 1 :(得分:0)
将其解析为JSON数组
let data = stringArray.data(using: .utf8)
do{
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String]
let first= json?[0] as? String
dump(first)
}catch let error{
}