Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define char array in Swift language

Here is my C code in an Objective-C method

char addressBuffer[100];

But how to define this char in Swift language?

I try something like this but this doesn't work:

var addressBuffer : CChar(100)

Here is the documentation https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/buildingcocoaapps/InteractingWithCAPIs.html

like image 362
szu Avatar asked Jun 20 '14 15:06

szu


People also ask

How do you define a char array?

A character array is a sequence of characters, just as a numeric array is a sequence of numbers. A typical use is to store a short piece of text as a row of characters in a character vector.

How do you declare an array in Swift?

We declare an array in Swift by using a list of values surrounded by square brackets. Line 1 shows how to explicitly declare an array of integers. Line 2 accomplishes the same thing as we initialize the array with value [1, 2] and Swift infers from that that it's an array of integers.

What is the datatype of array in Swift?

The type of a Swift array is written in full as Array<Element> , where Element is the type of values the array is allowed to store. You can also write the type of an array in shorthand form as [Element] .


2 Answers

that is the way to get a nice unicode character array in Swfit:

var charArray: Array<Character> = Array(count: 100, repeatedValue: "?")

if fills your array with 100 question marks, initially.

update

with CChar, for instance:

var charArray: Array<CChar> = Array(count: 100, repeatedValue: 32) // 32 is the ascii space
like image 57
holex Avatar answered Oct 05 '22 14:10

holex


This Swift code seems to allocate something usable as a C char array of size 100 (for C interoperation needs):

var addressBuffer = [Int8](count: 100, repeatedValue: 0)

// test it
addressBuffer[0] = 65 // 'A'
addressBuffer.withUnsafePointerToElements() { (addrBuffPtr : UnsafePointer<CChar>) -> () in
      // use pointer to memory
      var x0 = addrBuffPtr.memory
      println("The ASCII value at index 0 is \(x0)")

      var myCOpaquePointer = COpaquePointer(addrBuffPtr)
      // use C pointer for interoperation calls
}
like image 37
hotpaw2 Avatar answered Oct 05 '22 12:10

hotpaw2