17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftで"hw.machine"を取得する

Last updated at Posted at 2014-06-13

sysctlbyname関数で"hw.machine"の値を取得するコードをSwiftで書き直すとき、Cの部分をどうするかでちょっと手間取ったのでメモとして残します。
参考:
Interacting with C APIs
Collection Types

func platformString() -> String {

	let name = "hw.machine"
	let cName = (name as NSString).UTF8String //Cの文字列を作成

	//サイズを取得
	var size: Int = 0 //size_tの代わりにInt
	sysctlbyname(cName, nil, &size, nil, 0)

	//取得したサイズでCCharの配列を初期化
	//*Xcode6-Beta4からCChar[]を[CChar]に変更
	var machine = [CChar](count: size / sizeof(CChar), repeatedValue: 0)
		
	//値を取得
	sysctlbyname(cName, &machine, &size, nil, 0)

	//Stringに変換
	return NSString(bytes: machine, length: size, encoding: NSUTF8StringEncoding) as String

}
17
17
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?