Swift에서 빈 배열을 만드는 방법은 무엇입니까?
Swift에서 배열을 만드는 방법과 혼동됩니다. 빈 배열을 만드는 방법은 몇 가지입니까?
여기 있습니다 :
var yourArray = [String]()
위의 내용은 문자열뿐만 아니라 다른 유형에도 적용됩니다. 단지 예일뿐입니다.
그것에 값 추가
결국에는 값을 추가하고 싶을 것입니다!
yourArray.append("String Value")
또는
let someString = "You can also pass a string variable, like this!"
yourArray.append(someString)
삽입하여 추가
값이 몇 개 있으면 추가하는 대신 새 값을 삽입 할 수 있습니다. 예를 들어, 배열의 시작 부분에 새 오브젝트를 삽입하려는 경우 (끝에 오브젝트를 추가하는 대신) :
yourArray.insert("Hey, I'm first!", atIndex: 0)
또는 변수를 사용하여 삽입물을보다 유연하게 만들 수 있습니다.
let lineCutter = "I'm going to be first soon."
let positionToInsertAt = 0
yourArray.insert(lineCutter, atIndex: positionToInsertAt)
결국 물건을 제거하고 싶을 수도 있습니다
var yourOtherArray = ["MonkeysRule", "RemoveMe", "SwiftRules"]
yourOtherArray.removeAtIndex(1)
위의 내용은 배열에서 값의 위치를 알 때 (즉, 색인 값을 알고있을 때) 효과적입니다. 인덱스 값이 0에서 시작하면 두 번째 항목은 인덱스 1에있게됩니다.
인덱스를 몰라도 값 제거
그러나 그렇지 않으면 어떻게해야합니까? yourOtherArray에 수백 개의 값이 있고 "RemoveMe"와 동일한 값을 제거하려는 경우 어떻게해야합니까?
if let indexValue = yourOtherArray.indexOf("RemoveMe") {
yourOtherArray.removeAtIndex(indexValue)
}
시작해야합니다!
var myArr1 = [AnyObject]()
모든 객체를 저장할 수 있습니다
var myArr2 = [String]()
문자열 만 저장할 수 있습니다
당신은 사용할 수 있습니다
var firstNames: [String] = []
스위프트 3
Swift에서 빈 배열을 만드는 세 가지 방법이 있으며 단축 구문 방식이 항상 선호됩니다.
방법 1 : 속기 구문
var arr = [Int]()
방법 2 : 배열 이니셜 라이저
var arr = Array<Int>()
방법 3 : 배열 리터럴이있는 배열
var arr:[Int] = []
방법 4 : 신용은 @BallpointBen으로 이동
var arr:Array<Int> = []
신속하게 어레이를 생성 / 초기화하는 두 가지 주요 방법이 있습니다.
var myArray = [Double]()
이것은 복식 배열을 만듭니다.
var myDoubles = [Double](count: 5, repeatedValue: 2.0)
이것은 2.0의 값으로 초기화 된 5 배의 배열을 만듭니다.
빈 문자열 배열을 선언하려면 5 가지 방법으로 수행 할 수 있습니다.
var myArray: Array<String> = Array()
var myArray = [String]()
var myArray: [String] = []
var myArray = Array<String>()
var myArray:Array<String> = []
모든 유형의 배열 :-
var myArray: Array<AnyObject> = Array()
var myArray = [AnyObject]()
var myArray: [AnyObject] = []
var myArray = Array<AnyObject>()
var myArray:Array<AnyObject> = []
정수형 배열 :-
var myArray: Array<Int> = Array()
var myArray = [Int]()
var myArray: [Int] = []
var myArray = Array<Int>()
var myArray:Array<Int> = []
Here are some common tasks in Swift 4 you can use as a reference until you get used to things.
let emptyArray = [String]()
let emptyDouble: [Double] = []
let preLoadArray = Array(repeating: 0, count: 10) // initializes array with 10 default values of the number 0
let arrayMix = [1, "two", 3] as [Any]
var arrayNum = [1, 2, 3]
var array = ["1", "two", "3"]
array[1] = "2"
array.append("4")
array += ["5", "6"]
array.insert("0", at: 0)
array[0] = "Zero"
array.insert(contentsOf: ["-3", "-2", "-1"], at: 0)
array.remove(at: 0)
array.removeLast()
array = ["Replaces all indexes with this"]
array.removeAll()
for item in arrayMix {
print(item)
}
for (index, element) in array.enumerated() {
print(index)
print(element)
}
for (index, _) in arrayNum.enumerated().reversed() {
arrayNum.remove(at: index)
}
let words = "these words will be objects in an array".components(separatedBy: " ")
print(words[1])
var names = ["Jemima", "Peter", "David", "Kelly", "Isabella", "Adam"]
names.sort() // sorts names in alphabetical order
let nums = [1, 1234, 12, 123, 0, 999]
print(nums.sorted()) // sorts numbers from lowest to highest
Array in swift is written as **Array < Element > **, where Element is the type of values the array is allowed to store.
Array can be initialized as :
let emptyArray = [String]()
It shows that its an array of type string
The type of the emptyArray variable is inferred to be [String] from the type of the initializer.
For Creating the array of type string with elements
var groceryList: [String] = ["Eggs", "Milk"]
groceryList has been initialized with two items
The groceryList variable is declared as “an array of string values”, written as [String]. This particular array has specified a value type of String, it is allowed to store String values only.
There are various properities of array like :
- To check if array has elements (If array is empty or not)
isEmpty property( Boolean ) for checking whether the count property is equal to 0:
if groceryList.isEmpty {
print("The groceryList list is empty.")
} else {
print("The groceryList is not empty.")
}
- Appending(adding) elements in array
You can add a new item to the end of an array by calling the array’s append(_:) method:
groceryList.append("Flour")
groceryList now contains 3 items.
Alternatively, append an array of one or more compatible items with the addition assignment operator (+=):
groceryList += ["Baking Powder"]
groceryList now contains 4 items
groceryList += ["Chocolate Spread", "Cheese", "Peanut Butter"]
groceryList now contains 7 items
you can remove the array content with passing the array index or you can remove all
var array = [String]()
print(array)
array.append("MY NAME")
print(array)
array.removeFirst()
print(array)
array.append("MY NAME")
array.removeLast()
array.append("MY NAME1")
array.append("MY NAME2")
print(array)
array.removeAll()
print(array)
Swift 5
// Create an empty array
var emptyArray = [String]()
// Add values to array by appending (Adds values as the last element)
emptyArray.append("Apple")
emptyArray.append("Oppo")
// Add values to array by inserting (Adds to a specified position of the list)
emptyArray.insert("Samsung", at: 0)
// Remove elements from an array by index number
emptyArray.remove(at: 2)
// Remove elements by specifying the element
if let removeElement = emptyArray.firstIndex(of: "Samsung") {
emptyArray.remove(at: removeElement)
}
A similar answer is given but that doesn't work for the latest version of Swift (Swift 5), so here is the updated answer. Hope it helps! :)
Compatible with: Xcode 6.0.1+
You can create an empty array by specifying the Element type of your array in the declaration.
For example:
// Shortened forms are preferred
var emptyDoubles: [Double] = []
// The full type name is also allowed
var emptyFloats: Array<Float> = Array()
Example from the apple developer page (Array):
Hope this helps anyone stumbling onto this page.
As per Swift 5
// An array of 'Int' elements
let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]
// An array of 'String' elements
let streets = ["Albemarle", "Brandywine", "Chesapeake"]
// Shortened forms are preferred
var emptyDoubles: [Double] = []
// The full type name is also allowed
var emptyFloats: Array<Float> = Array()
Initiating an array with a predefined count:
Array(repeating: 0, count: 10)
I often use this for mapping statements where I need a specified number of mock objects. For example,
let myObjects: [MyObject] = Array(repeating: 0, count: 10).map { _ in return MyObject() }
참고URL : https://stackoverflow.com/questions/30430550/how-to-create-an-empty-array-in-swift
'Programing' 카테고리의 다른 글
ImportError : 이름이 apiclient.discovery 인 모듈이 없습니다. (0) | 2020.06.27 |
---|---|
Octave-Gnuplot-AquaTerm 오류 : 터미널 아쿠아 확장 제목“그림 1”… 알 수없는 터미널 유형 설정” (0) | 2020.06.27 |
void async 메소드 대기 (0) | 2020.06.26 |
배치 파일에서 앰퍼샌드를 이스케이프 처리하려면 어떻게해야합니까? (0) | 2020.06.26 |
PHP에서 정적 클래스를 만들 수 있습니까 (C # 에서처럼)? (0) | 2020.06.26 |