repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
PiXeL16/BudgetShare | BudgetShareTests/Modules/Login/Wireframe/LoginWireframeProviderSpec.swift | 1 | 649 | import Nimble
import Quick
@testable import BudgetShare
class LoginWireframeProviderSpec: QuickSpec {
override func spec() {
describe("The login wireframe provider") {
var subject: LoginWireframeProvider!
var view: MockLoginView!
beforeEach {
view = MockLoginView()
subject = LoginWireframeProvider(root: nil, view: view)
}
it("Inits with correct values") {
expect(view.presenter).toNot(beNil())
expect(subject).toNot(beNil())
}
}
}
}
| mit |
Tatoeba/tatoeba-ios | Tatoeba/Common/Networking/ImageRequest.swift | 1 | 693 | //
// ImageRequest.swift
// Tatoeba
//
// Created by Jack Cook on 8/6/17.
// Copyright © 2017 Tatoeba. All rights reserved.
//
import Alamofire
import UIKit
/// Returns an image from Tatoeba.
class ImageRequest: TatoebaRequest {
typealias ResponseData = UIImage
typealias Value = UIImage
let endpoint: String
var parameters: Parameters {
return [String: String]()
}
var responseType: TatoebaResponseType {
return .image
}
init(endpoint: String) {
self.endpoint = endpoint
}
func handleRequest(_ image: UIImage?, _ completion: @escaping (UIImage?) -> Void) {
completion(image)
}
}
| mit |
xusader/firefox-ios | Client/Frontend/Browser/PasswordHelper.swift | 3 | 12657 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import WebKit
private let SaveButtonTitle = NSLocalizedString("Save", comment: "Button to save the user's password")
private let NotNowButtonTitle = NSLocalizedString("Not now", comment: "Button to not save the user's password")
private let UpdateButtonTitle = NSLocalizedString("Update", comment: "Button to update the user's password")
private let CancelButtonTitle = NSLocalizedString("Cancel", comment: "Authentication prompt cancel button")
private let LoginButtonTitle = NSLocalizedString("Login", comment: "Authentication prompt login button")
class PasswordHelper: BrowserHelper {
private weak var browser: Browser?
private let profile: Profile
private var snackBar: SnackBar?
private static let MaxAuthenticationAttempts = 3
class func name() -> String {
return "PasswordHelper"
}
required init(browser: Browser, profile: Profile) {
self.browser = browser
self.profile = profile
if let path = NSBundle.mainBundle().pathForResource("PasswordHelper", ofType: "js") {
if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as? String {
var userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
browser.webView.configuration.userContentController.addUserScript(userScript)
}
}
}
func scriptMessageHandlerName() -> String? {
return "passwordsManagerMessageHandler"
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
// println("DEBUG: passwordsManagerMessageHandler message: \(message.body)")
var res = message.body as! [String: String]
let type = res["type"]
if let url = browser?.url {
if type == "request" {
res["username"] = ""
res["password"] = ""
let password = Password.fromScript(url, script: res)
requestPasswords(password, requestId: res["requestId"]!)
} else if type == "submit" {
let password = Password.fromScript(url, script: res)
setPassword(Password.fromScript(url, script: res))
}
}
}
class func replace(base: String, keys: [String], replacements: [String]) -> NSMutableAttributedString {
var ranges = [NSRange]()
var string = base
for (index, key) in enumerate(keys) {
let replace = replacements[index]
let range = string.rangeOfString(key,
options: NSStringCompareOptions.LiteralSearch,
range: nil,
locale: nil)!
string.replaceRange(range, with: replace)
let nsRange = NSMakeRange(distance(string.startIndex, range.startIndex),
count(replace))
ranges.append(nsRange)
}
var attributes = [NSObject: AnyObject]()
attributes[NSFontAttributeName] = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Medium" : "HelveticaNeue", size: 13)
attributes[NSForegroundColorAttributeName] = UIColor.darkGrayColor()
var attr = NSMutableAttributedString(string: string, attributes: attributes)
for (index, range) in enumerate(ranges) {
attr.addAttribute(NSFontAttributeName, value: UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Bold" : "HelveticaNeue-Medium", size: 13)!, range: range)
}
return attr
}
private func setPassword(password: Password) {
profile.passwords.get(QueryOptions(filter: password.hostname), complete: { data in
for i in 0..<data.count {
let savedPassword = data[i] as! Password
if savedPassword.username == password.username {
if savedPassword.password == password.password {
return
}
self.promptUpdate(password)
return
}
}
self.promptSave(password)
})
}
private func promptSave(password: Password) {
let promptStringFormat = NSLocalizedString("Do you want to save the password for %@ on %@?", comment: "Prompt for saving a password. The first parameter is the username being saved. The second parameter is the hostname of the site.")
let promptMessage = NSAttributedString(string: String(format: promptStringFormat, password.username, password.hostname))
if snackBar != nil {
browser?.removeSnackbar(snackBar!)
}
snackBar = CountdownSnackBar(attrText: promptMessage,
img: UIImage(named: "lock_verified"),
buttons: [
SnackButton(title: SaveButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
self.profile.passwords.add(password) { success in
// nop
}
}),
SnackButton(title: NotNowButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
return
})
])
browser?.addSnackbar(snackBar!)
}
private func promptUpdate(password: Password) {
let promptStringFormat = NSLocalizedString("Do you want to update the password for %@ on %@?", comment: "Prompt for updating a password. The first parameter is the username being saved. The second parameter is the hostname of the site.")
let formatted = String(format: promptStringFormat, password.username, password.hostname)
let promptMessage = NSAttributedString(string: formatted)
if snackBar != nil {
browser?.removeSnackbar(snackBar!)
}
snackBar = CountdownSnackBar(attrText: promptMessage,
img: UIImage(named: "lock_verified"),
buttons: [
SnackButton(title: UpdateButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
self.profile.passwords.add(password) { success in
// println("Add password \(success)")
}
}),
SnackButton(title: NotNowButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
return
})
])
browser?.addSnackbar(snackBar!)
}
private func requestPasswords(password: Password, requestId: String) {
profile.passwords.get(QueryOptions(filter: password.hostname), complete: { (cursor) -> Void in
var logins = [[String: String]]()
for i in 0..<cursor.count {
let password = cursor[i] as! Password
logins.append(password.toDict())
}
let jsonObj: [String: AnyObject] = [
"requestId": requestId,
"name": "RemoteLogins:loginsFound",
"logins": logins
]
let json = JSON(jsonObj)
let src = "window.__firefox__.passwords.inject(\(json.toString()))"
self.browser?.webView.evaluateJavaScript(src, completionHandler: { (obj, err) -> Void in
})
})
}
func handleAuthRequest(viewController: UIViewController, challenge: NSURLAuthenticationChallenge, completion: (password: Password?) -> Void) {
// If there have already been too many login attempts, we'll just fail.
if challenge.previousFailureCount >= PasswordHelper.MaxAuthenticationAttempts {
completion(password: nil)
return
}
var credential = challenge.proposedCredential
// If we were passed an initial set of credentials from iOS, try and use them.
if let proposed = credential {
if !(proposed.user?.isEmpty ?? true) {
if challenge.previousFailureCount == 0 {
completion(password: Password(credential: credential!, protectionSpace: challenge.protectionSpace))
return
}
} else {
credential = nil
}
}
if let credential = credential {
// If we have some credentials, we'll show a prompt with them.
let password = Password(credential: credential, protectionSpace: challenge.protectionSpace)
promptForUsernamePassword(viewController, password: password, completion: completion)
} else {
// Otherwise, try to look one up
let options = QueryOptions(filter: challenge.protectionSpace.host, filterType: .None, sort: .None)
profile.passwords.get(options, complete: { (cursor) -> Void in
var password = cursor[0] as? Password
if password == nil {
password = Password(credential: nil, protectionSpace: challenge.protectionSpace)
}
self.promptForUsernamePassword(viewController, password: password!, completion: completion)
})
}
}
private func promptForUsernamePassword(viewController: UIViewController, password: Password, completion: (password: Password?) -> Void) {
if password.hostname.isEmpty {
println("Unable to show a password prompt without a hostname")
completion(password: nil)
}
let alert: UIAlertController
let title = NSLocalizedString("Authentication required", comment: "Authentication prompt title")
if !password.httpRealm.isEmpty {
let msg = NSLocalizedString("A username and password are being requested by %@. The site says: %@", comment: "Authentication prompt message with a realm. First parameter is the hostname. Second is the realm string")
let formatted = NSString(format: msg, password.hostname, password.httpRealm) as String
alert = UIAlertController(title: title, message: formatted, preferredStyle: UIAlertControllerStyle.Alert)
} else {
let msg = NSLocalizedString("A username and password are being requested by %@.", comment: "Authentication prompt message with no realm. Parameter is the hostname of the site")
let formatted = NSString(format: msg, password.hostname) as String
alert = UIAlertController(title: title, message: formatted, preferredStyle: UIAlertControllerStyle.Alert)
}
// Add a login button.
let action = UIAlertAction(title: LoginButtonTitle,
style: UIAlertActionStyle.Default) { (action) -> Void in
let user = (alert.textFields?[0] as! UITextField).text
let pass = (alert.textFields?[1] as! UITextField).text
let credential = NSURLCredential(user: user, password: pass, persistence: .ForSession)
let password = Password(credential: credential, protectionSpace: password.protectionSpace)
completion(password: password)
self.setPassword(password)
}
alert.addAction(action)
// Add a cancel button.
let cancel = UIAlertAction(title: CancelButtonTitle, style: UIAlertActionStyle.Cancel) { (action) -> Void in
completion(password: nil)
return
}
alert.addAction(cancel)
// Add a username textfield.
alert.addTextFieldWithConfigurationHandler { (textfield) -> Void in
textfield.placeholder = NSLocalizedString("Username", comment: "Username textbox in Authentication prompt")
textfield.text = password.username
}
// Add a password textfield.
alert.addTextFieldWithConfigurationHandler { (textfield) -> Void in
textfield.placeholder = NSLocalizedString("Password", comment: "Password textbox in Authentication prompt")
textfield.secureTextEntry = true
textfield.text = password.password
}
viewController.presentViewController(alert, animated: true) { () -> Void in }
}
} | mpl-2.0 |
SwiftKidz/Slip | Sources/Classes/FlowResultsHandler.swift | 1 | 2609 | /*
MIT License
Copyright (c) 2016 SwiftKidz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
final class FlowResultsHandler {
fileprivate var rawResults: [FlowOpResult] = []
fileprivate let resultsQueue: DispatchQueue
fileprivate let finishHandler: ([FlowOpResult], Error?) -> Void
fileprivate let numberOfResultsToFinish: Int
fileprivate var stop: Bool = false
init(maxOps: Int = -1, onFinish: @escaping ([FlowOpResult], Error?) -> Void) {
resultsQueue = DispatchQueue(label: "com.slip.flow.flowOperationResultsHandler.resultsQueue")
finishHandler = onFinish
numberOfResultsToFinish = maxOps
}
}
extension FlowResultsHandler {
var currentResults: [FlowOpResult] {
var res: [FlowOpResult]!
resultsQueue.sync { res = rawResults }
res = rawResults
return res
}
}
extension FlowResultsHandler {
func addNewResult(_ result: FlowOpResult) {
resultsQueue.sync {
guard !self.stop else { return }
guard result.error == nil else {
self.finish(result.error)
return
}
self.rawResults.append(result)
guard self.rawResults.count == self.numberOfResultsToFinish else { return }
self.finish()
}
}
}
extension FlowResultsHandler {
func finish(_ error: Error? = nil) {
stop = true
let handler = finishHandler
let results = rawResults
let error = error
DispatchQueue.global().async {
handler(results, error)
}
}
}
| mit |
SuPair/firefox-ios | Push/PushCrypto.swift | 1 | 14173 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import FxA
/// Class to wrap ecec which does the encryption, decryption and key generation with OpenSSL.
/// This supports aesgcm and the newer aes128gcm.
/// For each standard of decryption, two methods are supplied: one with Data parameters and return value,
/// and one with a String based one.
class PushCrypto {
// Stateless, we provide a singleton for convenience.
open static var sharedInstance = PushCrypto()
}
// AES128GCM
extension PushCrypto {
func aes128gcm(payload data: String, decryptWith privateKey: String, authenticateWith authKey: String) throws -> String {
guard let authSecret = authKey.base64urlSafeDecodedData,
let rawRecvPrivKey = privateKey.base64urlSafeDecodedData,
let payload = data.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let decrypted = try aes128gcm(payload: payload,
decryptWith: rawRecvPrivKey,
authenticateWith: authSecret)
guard let plaintext = decrypted.utf8EncodedString else {
throw PushCryptoError.utf8EncodingError
}
return plaintext
}
func aes128gcm(payload: Data, decryptWith rawRecvPrivKey: Data, authenticateWith authSecret: Data) throws -> Data {
var plaintextLen = ece_aes128gcm_plaintext_max_length(payload.getBytes(), payload.count) + 1
var plaintext = [UInt8](repeating: 0, count: plaintextLen)
let err = ece_webpush_aes128gcm_decrypt(
rawRecvPrivKey.getBytes(), rawRecvPrivKey.count,
authSecret.getBytes(), authSecret.count,
payload.getBytes(), payload.count,
&plaintext, &plaintextLen)
if err != ECE_OK {
throw PushCryptoError.decryptionError(errCode: err)
}
return Data(bytes: plaintext, count: plaintextLen)
}
func aes128gcm(plaintext: String, encryptWith rawRecvPubKey: String, authenticateWith authSecret: String, rs: Int = 4096, padLen: Int = 0) throws -> String {
guard let rawRecvPubKey = rawRecvPubKey.base64urlSafeDecodedData,
let authSecret = authSecret.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let plaintextData = plaintext.utf8EncodedData
let payloadData = try aes128gcm(plaintext: plaintextData,
encryptWith: rawRecvPubKey,
authenticateWith: authSecret,
rs: rs, padLen: padLen)
guard let payload = payloadData.base64urlSafeEncodedString else {
throw PushCryptoError.base64EncodeError
}
return payload
}
func aes128gcm(plaintext: Data, encryptWith rawRecvPubKey: Data, authenticateWith authSecret: Data, rs rsInt: Int = 4096, padLen: Int = 0) throws -> Data {
let rs = UInt32(rsInt)
// rs needs to be >= 18.
assert(rsInt >= Int(ECE_AES128GCM_MIN_RS))
var payloadLen = ece_aes128gcm_payload_max_length(rs, padLen, plaintext.count) + 1
var payload = [UInt8](repeating: 0, count: payloadLen)
let err = ece_webpush_aes128gcm_encrypt(rawRecvPubKey.getBytes(), rawRecvPubKey.count,
authSecret.getBytes(), authSecret.count,
rs, padLen,
plaintext.getBytes(), plaintext.count,
&payload, &payloadLen)
if err != ECE_OK {
throw PushCryptoError.encryptionError(errCode: err)
}
return Data(bytes: payload, count: payloadLen)
}
}
// AESGCM
extension PushCrypto {
func aesgcm(ciphertext data: String, withHeaders headers: PushCryptoHeaders, decryptWith privateKey: String, authenticateWith authKey: String) throws -> String {
guard let authSecret = authKey.base64urlSafeDecodedData,
let rawRecvPrivKey = privateKey.base64urlSafeDecodedData,
let ciphertext = data.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let decrypted = try aesgcm(ciphertext: ciphertext,
withHeaders: headers,
decryptWith: rawRecvPrivKey,
authenticateWith: authSecret)
guard let plaintext = decrypted.utf8EncodedString else {
throw PushCryptoError.utf8EncodingError
}
return plaintext
}
func aesgcm(ciphertext: Data, withHeaders headers: PushCryptoHeaders, decryptWith rawRecvPrivKey: Data, authenticateWith authSecret: Data) throws -> Data {
let saltLength = Int(ECE_SALT_LENGTH)
var salt = [UInt8](repeating: 0, count: saltLength)
let rawSenderPubKeyLength = Int(ECE_WEBPUSH_PUBLIC_KEY_LENGTH)
var rawSenderPubKey = [UInt8](repeating: 0, count: rawSenderPubKeyLength)
var rs = UInt32(0)
let paramsErr = ece_webpush_aesgcm_headers_extract_params(
headers.cryptoKey, headers.encryption,
&salt, saltLength,
&rawSenderPubKey, rawSenderPubKeyLength,
&rs)
if paramsErr != ECE_OK {
throw PushCryptoError.decryptionError(errCode: paramsErr)
}
var plaintextLen = ece_aesgcm_plaintext_max_length(rs, ciphertext.count) + 1
var plaintext = [UInt8](repeating: 0, count: plaintextLen)
let decryptErr = ece_webpush_aesgcm_decrypt(
rawRecvPrivKey.getBytes(), rawRecvPrivKey.count,
authSecret.getBytes(), authSecret.count,
&salt, salt.count,
&rawSenderPubKey, rawSenderPubKey.count,
rs,
ciphertext.getBytes(), ciphertext.count,
&plaintext, &plaintextLen)
if decryptErr != ECE_OK {
throw PushCryptoError.decryptionError(errCode: decryptErr)
}
return Data(bytes: plaintext, count: plaintextLen)
}
func aesgcm(plaintext: String, encryptWith rawRecvPubKey: String, authenticateWith authSecret: String, rs: Int, padLen: Int) throws -> (headers: PushCryptoHeaders, ciphertext: String) {
guard let rawRecvPubKey = rawRecvPubKey.base64urlSafeDecodedData,
let authSecret = authSecret.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let plaintextData = plaintext.utf8EncodedData
let (headers, messageData) = try aesgcm(
plaintext: plaintextData,
encryptWith: rawRecvPubKey,
authenticateWith: authSecret,
rs: rs, padLen: padLen)
guard let message = messageData.base64urlSafeEncodedString else {
throw PushCryptoError.base64EncodeError
}
return (headers, message)
}
func aesgcm(plaintext: Data, encryptWith rawRecvPubKey: Data, authenticateWith authSecret: Data, rs rsInt: Int, padLen: Int) throws -> (headers: PushCryptoHeaders, data: Data) {
let rs = UInt32(rsInt)
// rs needs to be >= 3.
assert(rsInt >= Int(ECE_AESGCM_MIN_RS))
var ciphertextLength = ece_aesgcm_ciphertext_max_length(rs, padLen, plaintext.count) + 1
var ciphertext = [UInt8](repeating: 0, count: ciphertextLength)
let saltLength = Int(ECE_SALT_LENGTH)
var salt = [UInt8](repeating: 0, count: saltLength)
let rawSenderPubKeyLength = Int(ECE_WEBPUSH_PUBLIC_KEY_LENGTH)
var rawSenderPubKey = [UInt8](repeating: 0, count: rawSenderPubKeyLength)
let encryptErr = ece_webpush_aesgcm_encrypt(rawRecvPubKey.getBytes(), rawRecvPubKey.count,
authSecret.getBytes(), authSecret.count,
rs, padLen,
plaintext.getBytes(), plaintext.count,
&salt, saltLength,
&rawSenderPubKey, rawSenderPubKeyLength,
&ciphertext, &ciphertextLength)
if encryptErr != ECE_OK {
throw PushCryptoError.encryptionError(errCode: encryptErr)
}
var cryptoKeyHeaderLength = 0
var encryptionHeaderLength = 0
let paramsSizeErr = ece_webpush_aesgcm_headers_from_params(
salt, saltLength,
rawSenderPubKey, rawSenderPubKeyLength,
rs,
nil, &cryptoKeyHeaderLength,
nil, &encryptionHeaderLength)
if paramsSizeErr != ECE_OK {
throw PushCryptoError.encryptionError(errCode: paramsSizeErr)
}
var cryptoKeyHeaderBytes = [CChar](repeating: 0, count: cryptoKeyHeaderLength)
var encryptionHeaderBytes = [CChar](repeating: 0, count: encryptionHeaderLength)
let paramsErr = ece_webpush_aesgcm_headers_from_params(
salt, saltLength,
rawSenderPubKey, rawSenderPubKeyLength,
rs,
&cryptoKeyHeaderBytes, &cryptoKeyHeaderLength,
&encryptionHeaderBytes, &encryptionHeaderLength)
if paramsErr != ECE_OK {
throw PushCryptoError.encryptionError(errCode: paramsErr)
}
guard let cryptoKeyHeader = String(data: Data(bytes: cryptoKeyHeaderBytes, count: cryptoKeyHeaderLength),
encoding: .ascii),
let encryptionHeader = String(data: Data(bytes: encryptionHeaderBytes, count: encryptionHeaderLength),
encoding: .ascii) else {
throw PushCryptoError.base64EncodeError
}
let headers = PushCryptoHeaders(encryption: encryptionHeader, cryptoKey: cryptoKeyHeader)
return (headers, Data(bytes: ciphertext, count: ciphertextLength))
}
}
extension PushCrypto {
func generateKeys() throws -> PushKeys {
// The subscription private key. This key should never be sent to the app
// server. It should be persisted with the endpoint and auth secret, and used
// to decrypt all messages sent to the subscription.
let privateKeyLength = Int(ECE_WEBPUSH_PRIVATE_KEY_LENGTH)
var rawRecvPrivKey = [UInt8](repeating: 0, count: privateKeyLength)
// The subscription public key. This key should be sent to the app server,
// and used to encrypt messages. The Push DOM API exposes the public key via
// `pushSubscription.getKey("p256dh")`.
let publicKeyLength = Int(ECE_WEBPUSH_PUBLIC_KEY_LENGTH)
var rawRecvPubKey = [UInt8](repeating: 0, count: publicKeyLength)
// The shared auth secret. This secret should be persisted with the
// subscription information, and sent to the app server. The DOM API exposes
// the auth secret via `pushSubscription.getKey("auth")`.
let authSecretLength = Int(ECE_WEBPUSH_AUTH_SECRET_LENGTH)
var authSecret = [UInt8](repeating: 0, count: authSecretLength)
let err = ece_webpush_generate_keys(
&rawRecvPrivKey, privateKeyLength,
&rawRecvPubKey, publicKeyLength,
&authSecret, authSecretLength)
if err != ECE_OK {
throw PushCryptoError.keyGenerationError(errCode: err)
}
guard let privKey = Data(bytes: rawRecvPrivKey, count: privateKeyLength).base64urlSafeEncodedString,
let pubKey = Data(bytes: rawRecvPubKey, count: publicKeyLength).base64urlSafeEncodedString,
let authKey = Data(bytes: authSecret, count: authSecretLength).base64urlSafeEncodedString else {
throw PushCryptoError.base64EncodeError
}
return PushKeys(p256dhPrivateKey: privKey, p256dhPublicKey: pubKey, auth: authKey)
}
}
struct PushKeys {
let p256dhPrivateKey: String
let p256dhPublicKey: String
let auth: String
}
enum PushCryptoError: Error {
case base64DecodeError
case base64EncodeError
case decryptionError(errCode: Int32)
case encryptionError(errCode: Int32)
case keyGenerationError(errCode: Int32)
case utf8EncodingError
}
struct PushCryptoHeaders {
let encryption: String
let cryptoKey: String
}
extension String {
/// Returns a base64 url safe decoding of the given string.
/// The string is allowed to be padded
/// What is padding?: http://stackoverflow.com/a/26632221
var base64urlSafeDecodedData: Data? {
// We call this method twice: once with the last two args as nil, 0 – this gets us the length
// of the decoded string.
let length = ece_base64url_decode(self, self.count, ECE_BASE64URL_REJECT_PADDING, nil, 0)
guard length > 0 else {
return nil
}
// The second time, we actually decode, and copy it into a made to measure byte array.
var bytes = [UInt8](repeating: 0, count: length)
let checkLength = ece_base64url_decode(self, self.count, ECE_BASE64URL_REJECT_PADDING, &bytes, length)
guard checkLength == length else {
return nil
}
return Data(bytes: bytes, count: length)
}
}
extension Data {
/// Returns a base64 url safe encoding of the given data.
var base64urlSafeEncodedString: String? {
let length = ece_base64url_encode(self.getBytes(), self.count, ECE_BASE64URL_OMIT_PADDING, nil, 0)
guard length > 0 else {
return nil
}
var bytes = [CChar](repeating: 0, count: length)
let checkLength = ece_base64url_encode(self.getBytes(), self.count, ECE_BASE64URL_OMIT_PADDING, &bytes, length)
guard checkLength == length else {
return nil
}
return String(data: Data(bytes: bytes, count: length), encoding: .ascii)
}
}
| mpl-2.0 |
carabina/SYNQueue | SYNQueueDemo/SYNQueueDemo/TaskCell.swift | 1 | 737 | //
// TaskCell.swift
// SYNQueueDemo
//
// Created by John Hurliman on 6/18/15.
// Copyright (c) 2015 Syntertainment. All rights reserved.
//
import UIKit
import SYNQueue
class TaskCell : UICollectionViewCell {
@IBOutlet weak var succeedButton: UIButton!
@IBOutlet weak var failButton: UIButton!
@IBOutlet weak var nameLabel: UILabel!
weak var task: SYNQueueTask? = nil
@IBAction func succeedTapped(sender: UIButton) {
if let task = task {
task.completed(nil)
}
}
@IBAction func failTapped(sender: UIButton) {
if let task = task {
let err = error("User tapped Fail on task \(task.taskID)")
task.completed(err)
}
}
}
| mit |
HabitRPG/habitrpg-ios | HabitRPG/Utilities/ImageManager.swift | 1 | 4012 | //
// ImageManager.swift
// Habitica
//
// Created by Phillip Thelen on 02.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Kingfisher
@objc
class ImageManager: NSObject {
static let baseURL = "https://habitica-assets.s3.amazonaws.com/mobileApp/images/"
private static let formatDictionary = [
"head_special_0": "gif",
"head_special_1": "gif",
"shield_special_0": "gif",
"weapon_special_0": "gif",
"slim_armor_special_0": "gif",
"slim_armor_special_1": "gif",
"broad_armor_special_0": "gif",
"broad_armor_special_1": "gif",
"weapon_special_critical": "gif",
"Pet-Wolf-Cerberus": "gif",
"armor_special_ks2019": "gif",
"slim_armor_special_ks2019": "gif",
"broad_armor_special_ks2019": "gif",
"eyewear_special_ks2019": "gif",
"head_special_ks2019": "gif",
"shield_special_ks2019": "gif",
"weapon_special_ks2019": "gif",
"Pet-Gryphon-Gryphatrice": "gif",
"Mount_Head_Gryphon-Gryphatrice": "gif",
"Mount_Body_Gryphon-Gryphatrice": "gif",
"background_clocktower": "gif",
"background_airship": "gif",
"background_steamworks": "gif",
"Pet_HatchingPotion_Veggie": "gif",
"Pet_HatchingPotion_Dessert": "gif",
"Pet-HatchingPotion-Dessert": "gif",
"quest_windup": "gif",
"Pet-HatchingPotion_Windup": "gif",
"Pet_HatchingPotion_Windup": "gif",
"Pet-HatchingPotion-Windup": "gif"
]
@objc
static func setImage(on imageView: NetworkImageView, name: String, extension fileExtension: String = "", completion: ((UIImage?, NSError?) -> Void)? = nil) {
if imageView.loadedImageName != name {
imageView.image = nil
}
imageView.loadedImageName = name
getImage(name: name, extension: fileExtension) { (image, error) in
if imageView.loadedImageName == name {
imageView.image = image
if let action = completion {
action(image, error)
}
}
}
}
@objc
static func getImage(name: String, extension fileExtension: String = "", completion: @escaping (UIImage?, NSError?) -> Void) {
guard let url = URL(string: "\(baseURL)\(name).\(getFormat(name: name, format: fileExtension))") else {
return
}
KingfisherManager.shared.retrieveImage(with: url, options: nil, progressBlock: nil) { (image, error, _, _) in
if let error = error {
print("Image loading error:", name, error.localizedDescription)
}
completion(image, error)
}
}
@objc
static func getImage(url urlString: String, completion: @escaping (UIImage?, NSError?) -> Void) {
guard let url = URL(string: urlString) else {
return
}
KingfisherManager.shared.retrieveImage(with: url, options: nil, progressBlock: nil) { (image, error, _, _) in
if let error = error {
print("Image loading error:", url, error.localizedDescription)
}
completion(image, error)
}
}
@objc
static func clearImageCache() {
ImageCache.default.clearDiskCache()
ImageCache.default.clearMemoryCache()
}
private static func getFormat(name: String, format: String) -> String {
if (!format.isEmpty) {
return format
}
return formatDictionary[name] ?? "png"
}
private static func substituteSprite(name: String?) -> String? {
for (key, value) in substitutions {
if let keyString = key as? String, name?.contains(keyString) == true {
return value as? String
}
}
return name
}
static var substitutions = ConfigRepository().dictionary(variable: .spriteSubstitutions)
}
| gpl-3.0 |
jmgc/swift | stdlib/public/core/ArraySlice.swift | 1 | 58650 | //===--- ArraySlice.swift -------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// - `ArraySlice<Element>` presents an arbitrary subsequence of some
// contiguous sequence of `Element`s.
//
//===----------------------------------------------------------------------===//
/// A slice of an `Array`, `ContiguousArray`, or `ArraySlice` instance.
///
/// The `ArraySlice` type makes it fast and efficient for you to perform
/// operations on sections of a larger array. Instead of copying over the
/// elements of a slice to new storage, an `ArraySlice` instance presents a
/// view onto the storage of a larger array. And because `ArraySlice`
/// presents the same interface as `Array`, you can generally perform the
/// same operations on a slice as you could on the original array.
///
/// For more information about using arrays, see `Array` and `ContiguousArray`,
/// with which `ArraySlice` shares most properties and methods.
///
/// Slices Are Views onto Arrays
/// ============================
///
/// For example, suppose you have an array holding the number of absences
/// from each class during a session.
///
/// let absences = [0, 2, 0, 4, 0, 3, 1, 0]
///
/// You want to compare the absences in the first half of the session with
/// those in the second half. To do so, start by creating two slices of the
/// `absences` array.
///
/// let midpoint = absences.count / 2
///
/// let firstHalf = absences[..<midpoint]
/// let secondHalf = absences[midpoint...]
///
/// Neither the `firstHalf` nor `secondHalf` slices allocate any new storage
/// of their own. Instead, each presents a view onto the storage of the
/// `absences` array.
///
/// You can call any method on the slices that you might have called on the
/// `absences` array. To learn which half had more absences, use the
/// `reduce(_:_:)` method to calculate each sum.
///
/// let firstHalfSum = firstHalf.reduce(0, +)
/// let secondHalfSum = secondHalf.reduce(0, +)
///
/// if firstHalfSum > secondHalfSum {
/// print("More absences in the first half.")
/// } else {
/// print("More absences in the second half.")
/// }
/// // Prints "More absences in the first half."
///
/// - Important: Long-term storage of `ArraySlice` instances is discouraged. A
/// slice holds a reference to the entire storage of a larger array, not
/// just to the portion it presents, even after the original array's lifetime
/// ends. Long-term storage of a slice may therefore prolong the lifetime of
/// elements that are no longer otherwise accessible, which can appear to be
/// memory and object leakage.
///
/// Slices Maintain Indices
/// =======================
///
/// Unlike `Array` and `ContiguousArray`, the starting index for an
/// `ArraySlice` instance isn't always zero. Slices maintain the same
/// indices of the larger array for the same elements, so the starting
/// index of a slice depends on how it was created, letting you perform
/// index-based operations on either a full array or a slice.
///
/// Sharing indices between collections and their subsequences is an important
/// part of the design of Swift's collection algorithms. Suppose you are
/// tasked with finding the first two days with absences in the session. To
/// find the indices of the two days in question, follow these steps:
///
/// 1) Call `firstIndex(where:)` to find the index of the first element in the
/// `absences` array that is greater than zero.
/// 2) Create a slice of the `absences` array starting after the index found in
/// step 1.
/// 3) Call `firstIndex(where:)` again, this time on the slice created in step
/// 2. Where in some languages you might pass a starting index into an
/// `indexOf` method to find the second day, in Swift you perform the same
/// operation on a slice of the original array.
/// 4) Print the results using the indices found in steps 1 and 3 on the
/// original `absences` array.
///
/// Here's an implementation of those steps:
///
/// if let i = absences.firstIndex(where: { $0 > 0 }) { // 1
/// let absencesAfterFirst = absences[(i + 1)...] // 2
/// if let j = absencesAfterFirst.firstIndex(where: { $0 > 0 }) { // 3
/// print("The first day with absences had \(absences[i]).") // 4
/// print("The second day with absences had \(absences[j]).")
/// }
/// }
/// // Prints "The first day with absences had 2."
/// // Prints "The second day with absences had 4."
///
/// In particular, note that `j`, the index of the second day with absences,
/// was found in a slice of the original array and then used to access a value
/// in the original `absences` array itself.
///
/// - Note: To safely reference the starting and ending indices of a slice,
/// always use the `startIndex` and `endIndex` properties instead of
/// specific values.
@frozen
public struct ArraySlice<Element>: _DestructorSafeContainer {
@usableFromInline
internal typealias _Buffer = _SliceBuffer<Element>
@usableFromInline
internal var _buffer: _Buffer
/// Initialization from an existing buffer does not have "array.init"
/// semantics because the caller may retain an alias to buffer.
@inlinable
internal init(_buffer: _Buffer) {
self._buffer = _buffer
}
/// Initialization from an existing buffer does not have "array.init"
/// semantics because the caller may retain an alias to buffer.
@inlinable
internal init(_buffer buffer: _ContiguousArrayBuffer<Element>) {
self.init(_buffer: _Buffer(_buffer: buffer, shiftedToStartIndex: 0))
}
}
//===--- private helpers---------------------------------------------------===//
extension ArraySlice {
/// Returns `true` if the array is native and does not need a deferred
/// type check. May be hoisted by the optimizer, which means its
/// results may be stale by the time they are used if there is an
/// inout violation in user code.
@inlinable
@_semantics("array.props.isNativeTypeChecked")
public // @testable
func _hoistableIsNativeTypeChecked() -> Bool {
return _buffer.arrayPropertyIsNativeTypeChecked
}
@inlinable
@_semantics("array.get_count")
internal func _getCount() -> Int {
return _buffer.count
}
@inlinable
@_semantics("array.get_capacity")
internal func _getCapacity() -> Int {
return _buffer.capacity
}
@inlinable
@_semantics("array.make_mutable")
internal mutating func _makeMutableAndUnique() {
if _slowPath(!_buffer.beginCOWMutation()) {
_buffer = _Buffer(copying: _buffer)
}
}
/// Marks the end of a mutation.
///
/// After a call to `_endMutation` the buffer must not be mutated until a call
/// to `_makeMutableAndUnique`.
@_alwaysEmitIntoClient
@_semantics("array.end_mutation")
internal mutating func _endMutation() {
_buffer.endCOWMutation()
}
/// Check that the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
@inlinable
@inline(__always)
internal func _checkSubscript_native(_ index: Int) {
_buffer._checkValidSubscript(index)
}
/// Check that the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
@inlinable
@_semantics("array.check_subscript")
public // @testable
func _checkSubscript(
_ index: Int, wasNativeTypeChecked: Bool
) -> _DependenceToken {
#if _runtime(_ObjC)
_buffer._checkValidSubscript(index)
#else
_buffer._checkValidSubscript(index)
#endif
return _DependenceToken()
}
/// Check that the specified `index` is valid, i.e. `0 ≤ index ≤ count`.
@inlinable
@_semantics("array.check_index")
internal func _checkIndex(_ index: Int) {
_precondition(index <= endIndex, "ArraySlice index is out of range")
_precondition(index >= startIndex, "ArraySlice index is out of range (before startIndex)")
}
@_semantics("array.get_element")
@inlinable // FIXME(inline-always)
@inline(__always)
public // @testable
func _getElement(
_ index: Int,
wasNativeTypeChecked: Bool,
matchingSubscriptCheck: _DependenceToken
) -> Element {
#if false
return _buffer.getElement(index, wasNativeTypeChecked: wasNativeTypeChecked)
#else
return _buffer.getElement(index)
#endif
}
@inlinable
@_semantics("array.get_element_address")
internal func _getElementAddress(_ index: Int) -> UnsafeMutablePointer<Element> {
return _buffer.subscriptBaseAddress + index
}
}
extension ArraySlice: _ArrayProtocol {
/// The total number of elements that the array can contain without
/// allocating new storage.
///
/// Every array reserves a specific amount of memory to hold its contents.
/// When you add elements to an array and that array begins to exceed its
/// reserved capacity, the array allocates a larger region of memory and
/// copies its elements into the new storage. The new storage is a multiple
/// of the old storage's size. This exponential growth strategy means that
/// appending an element happens in constant time, averaging the performance
/// of many append operations. Append operations that trigger reallocation
/// have a performance cost, but they occur less and less often as the array
/// grows larger.
///
/// The following example creates an array of integers from an array literal,
/// then appends the elements of another collection. Before appending, the
/// array allocates new storage that is large enough store the resulting
/// elements.
///
/// var numbers = [10, 20, 30, 40, 50]
/// // numbers.count == 5
/// // numbers.capacity == 5
///
/// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10))
/// // numbers.count == 10
/// // numbers.capacity == 10
@inlinable
public var capacity: Int {
return _getCapacity()
}
/// An object that guarantees the lifetime of this array's elements.
@inlinable
public // @testable
var _owner: AnyObject? {
return _buffer.owner
}
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
@inlinable
public var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? {
@inline(__always) // FIXME(TODO: JIRA): Hack around test failure
get { return _buffer.firstElementAddressIfContiguous }
}
@inlinable
internal var _baseAddress: UnsafeMutablePointer<Element> {
return _buffer.firstElementAddress
}
}
extension ArraySlice: RandomAccessCollection, MutableCollection {
/// The index type for arrays, `Int`.
///
/// `ArraySlice` instances are not always indexed from zero. Use `startIndex`
/// and `endIndex` as the bounds for any element access, instead of `0` and
/// `count`.
public typealias Index = Int
/// The type that represents the indices that are valid for subscripting an
/// array, in ascending order.
public typealias Indices = Range<Int>
/// The type that allows iteration over an array's elements.
public typealias Iterator = IndexingIterator<ArraySlice>
/// The position of the first element in a nonempty array.
///
/// `ArraySlice` instances are not always indexed from zero. Use `startIndex`
/// and `endIndex` as the bounds for any element access, instead of `0` and
/// `count`.
///
/// If the array is empty, `startIndex` is equal to `endIndex`.
@inlinable
public var startIndex: Int {
return _buffer.startIndex
}
/// The array's "past the end" position---that is, the position one greater
/// than the last valid subscript argument.
///
/// When you need a range that includes the last element of an array, use the
/// half-open range operator (`..<`) with `endIndex`. The `..<` operator
/// creates a range that doesn't include the upper bound, so it's always
/// safe to use with `endIndex`. For example:
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let i = numbers.firstIndex(of: 30) {
/// print(numbers[i ..< numbers.endIndex])
/// }
/// // Prints "[30, 40, 50]"
///
/// If the array is empty, `endIndex` is equal to `startIndex`.
@inlinable
public var endIndex: Int {
return _buffer.endIndex
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index immediately after `i`.
@inlinable
public func index(after i: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
// capable of creating partial specializations yet.
// NOTE: Range checks are not performed here, because it is done later by
// the subscript function.
return i + 1
}
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
@inlinable
public func formIndex(after i: inout Int) {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
// capable of creating partial specializations yet.
// NOTE: Range checks are not performed here, because it is done later by
// the subscript function.
i += 1
}
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index immediately before `i`.
@inlinable
public func index(before i: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
// capable of creating partial specializations yet.
// NOTE: Range checks are not performed here, because it is done later by
// the subscript function.
return i - 1
}
/// Replaces the given index with its predecessor.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
@inlinable
public func formIndex(before i: inout Int) {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
// capable of creating partial specializations yet.
// NOTE: Range checks are not performed here, because it is done later by
// the subscript function.
i -= 1
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from an
/// array's starting index and then prints the element at that position.
///
/// let numbers = [10, 20, 30, 40, 50]
/// let i = numbers.index(numbers.startIndex, offsetBy: 4)
/// print(numbers[i])
/// // Prints "50"
///
/// The value passed as `distance` must not offset `i` beyond the bounds of
/// the collection.
///
/// - Parameters:
/// - i: A valid index of the array.
/// - distance: The distance to offset `i`.
/// - Returns: An index offset by `distance` from the index `i`. If
/// `distance` is positive, this is the same value as the result of
/// `distance` calls to `index(after:)`. If `distance` is negative, this
/// is the same value as the result of `abs(distance)` calls to
/// `index(before:)`.
@inlinable
public func index(_ i: Int, offsetBy distance: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
// capable of creating partial specializations yet.
// NOTE: Range checks are not performed here, because it is done later by
// the subscript function.
return i + distance
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from an
/// array's starting index and then prints the element at that position. The
/// operation doesn't require going beyond the limiting `numbers.endIndex`
/// value, so it succeeds.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let i = numbers.index(numbers.startIndex,
/// offsetBy: 4,
/// limitedBy: numbers.endIndex) {
/// print(numbers[i])
/// }
/// // Prints "50"
///
/// The next example attempts to retrieve an index ten positions from
/// `numbers.startIndex`, but fails, because that distance is beyond the
/// index passed as `limit`.
///
/// let j = numbers.index(numbers.startIndex,
/// offsetBy: 10,
/// limitedBy: numbers.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `distance` must not offset `i` beyond the bounds of
/// the collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the array.
/// - distance: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If
/// `distance > 0`, `limit` has no effect if it is less than `i`.
/// Likewise, if `distance < 0`, `limit` has no effect if it is greater
/// than `i`.
/// - Returns: An index offset by `distance` from the index `i`, unless that
/// index would be beyond `limit` in the direction of movement. In that
/// case, the method returns `nil`.
///
/// - Complexity: O(1)
@inlinable
public func index(
_ i: Int, offsetBy distance: Int, limitedBy limit: Int
) -> Int? {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
// capable of creating partial specializations yet.
// NOTE: Range checks are not performed here, because it is done later by
// the subscript function.
let l = limit - i
if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l {
return nil
}
return i + distance
}
/// Returns the distance between two indices.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`.
@inlinable
public func distance(from start: Int, to end: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
// capable of creating partial specializations yet.
// NOTE: Range checks are not performed here, because it is done later by
// the subscript function.
return end - start
}
@inlinable
public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) {
// NOTE: This method is a no-op for performance reasons.
}
@inlinable
public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) {
// NOTE: This method is a no-op for performance reasons.
}
/// Accesses the element at the specified position.
///
/// The following example uses indexed subscripting to update an array's
/// second element. After assigning the new value (`"Butler"`) at a specific
/// position, that value is immediately available at that same position.
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// streets[1] = "Butler"
/// print(streets[1])
/// // Prints "Butler"
///
/// - Parameter index: The position of the element to access. `index` must be
/// greater than or equal to `startIndex` and less than `endIndex`.
///
/// - Complexity: Reading an element from an array is O(1). Writing is O(1)
/// unless the array's storage is shared with another array or uses a
/// bridged `NSArray` instance as its storage, in which case writing is
/// O(*n*), where *n* is the length of the array.
@inlinable
public subscript(index: Int) -> Element {
get {
// This call may be hoisted or eliminated by the optimizer. If
// there is an inout violation, this value may be stale so needs to be
// checked again below.
let wasNativeTypeChecked = _hoistableIsNativeTypeChecked()
// Make sure the index is in range and wasNativeTypeChecked is
// still valid.
let token = _checkSubscript(
index, wasNativeTypeChecked: wasNativeTypeChecked)
return _getElement(
index, wasNativeTypeChecked: wasNativeTypeChecked,
matchingSubscriptCheck: token)
}
_modify {
_makeMutableAndUnique() // makes the array native, too
_checkSubscript_native(index)
let address = _buffer.subscriptBaseAddress + index
yield &address.pointee
_endMutation();
}
}
/// Accesses a contiguous subrange of the array's elements.
///
/// The returned `ArraySlice` instance uses the same indices for the same
/// elements as the original array. In particular, that slice, unlike an
/// array, may have a nonzero `startIndex` and an `endIndex` that is not
/// equal to `count`. Always use the slice's `startIndex` and `endIndex`
/// properties instead of assuming that its indices start or end at a
/// particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let i = streetsSlice.firstIndex(of: "Evarts") // 4
/// print(streets[i!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of integers. The bounds of the range must be
/// valid indices of the array.
@inlinable
public subscript(bounds: Range<Int>) -> ArraySlice<Element> {
get {
_checkIndex(bounds.lowerBound)
_checkIndex(bounds.upperBound)
return ArraySlice(_buffer: _buffer[bounds])
}
set(rhs) {
_checkIndex(bounds.lowerBound)
_checkIndex(bounds.upperBound)
// If the replacement buffer has same identity, and the ranges match,
// then this was a pinned in-place modification, nothing further needed.
if self[bounds]._buffer.identity != rhs._buffer.identity
|| bounds != rhs.startIndex..<rhs.endIndex {
self.replaceSubrange(bounds, with: rhs)
}
}
}
/// The number of elements in the array.
@inlinable
public var count: Int {
return _getCount()
}
}
extension ArraySlice: ExpressibleByArrayLiteral {
/// Creates an array from the given array literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use an array literal. Instead, create a new array by using an array
/// literal as its value. To do this, enclose a comma-separated list of
/// values in square brackets.
///
/// Here, an array of strings is created from an array literal holding only
/// strings:
///
/// let ingredients: ArraySlice =
/// ["cocoa beans", "sugar", "cocoa butter", "salt"]
///
/// - Parameter elements: A variadic list of elements of the new array.
@inlinable
public init(arrayLiteral elements: Element...) {
self.init(_buffer: ContiguousArray(elements)._buffer)
}
}
extension ArraySlice: RangeReplaceableCollection {
/// Creates a new, empty array.
///
/// This is equivalent to initializing with an empty array literal.
/// For example:
///
/// var emptyArray = Array<Int>()
/// print(emptyArray.isEmpty)
/// // Prints "true"
///
/// emptyArray = []
/// print(emptyArray.isEmpty)
/// // Prints "true"
@inlinable
@_semantics("array.init.empty")
public init() {
_buffer = _Buffer()
}
/// Creates an array containing the elements of a sequence.
///
/// You can use this initializer to create an array from any other type that
/// conforms to the `Sequence` protocol. For example, you might want to
/// create an array with the integers from 1 through 7. Use this initializer
/// around a range instead of typing all those numbers in an array literal.
///
/// let numbers = Array(1...7)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 6, 7]"
///
/// You can also use this initializer to convert a complex sequence or
/// collection type back to an array. For example, the `keys` property of
/// a dictionary isn't an array with its own storage, it's a collection
/// that maps its elements from the dictionary only when they're
/// accessed, saving the time and space needed to allocate an array. If
/// you need to pass those keys to a method that takes an array, however,
/// use this initializer to convert that list from its type of
/// `LazyMapCollection<Dictionary<String, Int>, Int>` to a simple
/// `[String]`.
///
/// func cacheImagesWithNames(names: [String]) {
/// // custom image loading and caching
/// }
///
/// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302,
/// "Gold": 50, "Cerise": 320]
/// let colorNames = Array(namedHues.keys)
/// cacheImagesWithNames(colorNames)
///
/// print(colorNames)
/// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"
///
/// - Parameter s: The sequence of elements to turn into an array.
@inlinable
public init<S: Sequence>(_ s: S)
where S.Element == Element {
self.init(_buffer: s._copyToContiguousArray()._buffer)
}
/// Creates a new array containing the specified number of a single, repeated
/// value.
///
/// Here's an example of creating an array initialized with five strings
/// containing the letter *Z*.
///
/// let fiveZs = Array(repeating: "Z", count: 5)
/// print(fiveZs)
/// // Prints "["Z", "Z", "Z", "Z", "Z"]"
///
/// - Parameters:
/// - repeatedValue: The element to repeat.
/// - count: The number of times to repeat the value passed in the
/// `repeating` parameter. `count` must be zero or greater.
@inlinable
@_semantics("array.init")
public init(repeating repeatedValue: Element, count: Int) {
_precondition(count >= 0, "Can't construct ArraySlice with count < 0")
if count > 0 {
_buffer = ArraySlice._allocateBufferUninitialized(minimumCapacity: count)
_buffer.count = count
var p = _buffer.firstElementAddress
for _ in 0..<count {
p.initialize(to: repeatedValue)
p += 1
}
} else {
_buffer = _Buffer()
}
_endMutation()
}
@inline(never)
@usableFromInline
internal static func _allocateBufferUninitialized(
minimumCapacity: Int
) -> _Buffer {
let newBuffer = _ContiguousArrayBuffer<Element>(
_uninitializedCount: 0, minimumCapacity: minimumCapacity)
return _Buffer(_buffer: newBuffer, shiftedToStartIndex: 0)
}
/// Construct a ArraySlice of `count` uninitialized elements.
@inlinable
@_semantics("array.init")
internal init(_uninitializedCount count: Int) {
_precondition(count >= 0, "Can't construct ArraySlice with count < 0")
// Note: Sinking this constructor into an else branch below causes an extra
// Retain/Release.
_buffer = _Buffer()
if count > 0 {
// Creating a buffer instead of calling reserveCapacity saves doing an
// unnecessary uniqueness check. We disable inlining here to curb code
// growth.
_buffer = ArraySlice._allocateBufferUninitialized(minimumCapacity: count)
_buffer.count = count
}
// Can't store count here because the buffer might be pointing to the
// shared empty array.
_endMutation()
}
/// Entry point for `Array` literal construction; builds and returns
/// a ArraySlice of `count` uninitialized elements.
@inlinable
@_semantics("array.uninitialized")
internal static func _allocateUninitialized(
_ count: Int
) -> (ArraySlice, UnsafeMutablePointer<Element>) {
let result = ArraySlice(_uninitializedCount: count)
return (result, result._buffer.firstElementAddress)
}
//===--- basic mutations ------------------------------------------------===//
/// Reserves enough space to store the specified number of elements.
///
/// If you are adding a known number of elements to an array, use this method
/// to avoid multiple reallocations. This method ensures that the array has
/// unique, mutable, contiguous storage, with space allocated for at least
/// the requested number of elements.
///
/// Calling the `reserveCapacity(_:)` method on an array with bridged storage
/// triggers a copy to contiguous storage even if the existing storage
/// has room to store `minimumCapacity` elements.
///
/// For performance reasons, the size of the newly allocated storage might be
/// greater than the requested capacity. Use the array's `capacity` property
/// to determine the size of the new storage.
///
/// Preserving an Array's Geometric Growth Strategy
/// ===============================================
///
/// If you implement a custom data structure backed by an array that grows
/// dynamically, naively calling the `reserveCapacity(_:)` method can lead
/// to worse than expected performance. Arrays need to follow a geometric
/// allocation pattern for appending elements to achieve amortized
/// constant-time performance. The `Array` type's `append(_:)` and
/// `append(contentsOf:)` methods take care of this detail for you, but
/// `reserveCapacity(_:)` allocates only as much space as you tell it to
/// (padded to a round value), and no more. This avoids over-allocation, but
/// can result in insertion not having amortized constant-time performance.
///
/// The following code declares `values`, an array of integers, and the
/// `addTenQuadratic()` function, which adds ten more values to the `values`
/// array on each call.
///
/// var values: [Int] = [0, 1, 2, 3]
///
/// // Don't use 'reserveCapacity(_:)' like this
/// func addTenQuadratic() {
/// let newCount = values.count + 10
/// values.reserveCapacity(newCount)
/// for n in values.count..<newCount {
/// values.append(n)
/// }
/// }
///
/// The call to `reserveCapacity(_:)` increases the `values` array's capacity
/// by exactly 10 elements on each pass through `addTenQuadratic()`, which
/// is linear growth. Instead of having constant time when averaged over
/// many calls, the function may decay to performance that is linear in
/// `values.count`. This is almost certainly not what you want.
///
/// In cases like this, the simplest fix is often to simply remove the call
/// to `reserveCapacity(_:)`, and let the `append(_:)` method grow the array
/// for you.
///
/// func addTen() {
/// let newCount = values.count + 10
/// for n in values.count..<newCount {
/// values.append(n)
/// }
/// }
///
/// If you need more control over the capacity of your array, implement your
/// own geometric growth strategy, passing the size you compute to
/// `reserveCapacity(_:)`.
///
/// - Parameter minimumCapacity: The requested number of elements to store.
///
/// - Complexity: O(*n*), where *n* is the number of elements in the array.
@inlinable
@_semantics("array.mutate_unknown")
public mutating func reserveCapacity(_ minimumCapacity: Int) {
if !_buffer.beginCOWMutation() || _buffer.capacity < minimumCapacity {
let newBuffer = _ContiguousArrayBuffer<Element>(
_uninitializedCount: count, minimumCapacity: minimumCapacity)
_buffer._copyContents(
subRange: _buffer.indices,
initializing: newBuffer.firstElementAddress)
_buffer = _Buffer(
_buffer: newBuffer, shiftedToStartIndex: _buffer.startIndex)
}
_internalInvariant(capacity >= minimumCapacity)
_endMutation()
}
/// Copy the contents of the current buffer to a new unique mutable buffer.
/// The count of the new buffer is set to `oldCount`, the capacity of the
/// new buffer is big enough to hold 'oldCount' + 1 elements.
@inline(never)
@inlinable // @specializable
internal mutating func _copyToNewBuffer(oldCount: Int) {
let newCount = oldCount + 1
var newBuffer = _buffer._forceCreateUniqueMutableBuffer(
countForNewBuffer: oldCount, minNewCapacity: newCount)
_buffer._arrayOutOfPlaceUpdate(
&newBuffer, oldCount, 0)
}
@inlinable
@_semantics("array.make_mutable")
internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() {
if _slowPath(!_buffer.beginCOWMutation()) {
_copyToNewBuffer(oldCount: _buffer.count)
}
}
@inlinable
@_semantics("array.mutate_unknown")
internal mutating func _reserveCapacityAssumingUniqueBuffer(oldCount: Int) {
// Due to make_mutable hoisting the situation can arise where we hoist
// _makeMutableAndUnique out of loop and use it to replace
// _makeUniqueAndReserveCapacityIfNotUnique that precedes this call. If the
// array was empty _makeMutableAndUnique does not replace the empty array
// buffer by a unique buffer (it just replaces it by the empty array
// singleton).
// This specific case is okay because we will make the buffer unique in this
// function because we request a capacity > 0 and therefore _copyToNewBuffer
// will be called creating a new buffer.
let capacity = _buffer.capacity
_internalInvariant(capacity == 0 || _buffer.isMutableAndUniquelyReferenced())
if _slowPath(oldCount + 1 > capacity) {
_copyToNewBuffer(oldCount: oldCount)
}
}
@inlinable
@_semantics("array.mutate_unknown")
internal mutating func _appendElementAssumeUniqueAndCapacity(
_ oldCount: Int,
newElement: __owned Element
) {
_internalInvariant(_buffer.isMutableAndUniquelyReferenced())
_internalInvariant(_buffer.capacity >= _buffer.count + 1)
_buffer.count = oldCount + 1
(_buffer.firstElementAddress + oldCount).initialize(to: newElement)
}
/// Adds a new element at the end of the array.
///
/// Use this method to append a single element to the end of a mutable array.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.append(100)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 100]"
///
/// Because arrays increase their allocated capacity using an exponential
/// strategy, appending a single element to an array is an O(1) operation
/// when averaged over many calls to the `append(_:)` method. When an array
/// has additional capacity and is not sharing its storage with another
/// instance, appending an element is O(1). When an array needs to
/// reallocate storage before appending or its storage is shared with
/// another copy, appending is O(*n*), where *n* is the length of the array.
///
/// - Parameter newElement: The element to append to the array.
///
/// - Complexity: O(1) on average, over many calls to `append(_:)` on the
/// same array.
@inlinable
@_semantics("array.append_element")
public mutating func append(_ newElement: __owned Element) {
_makeUniqueAndReserveCapacityIfNotUnique()
let oldCount = _getCount()
_reserveCapacityAssumingUniqueBuffer(oldCount: oldCount)
_appendElementAssumeUniqueAndCapacity(oldCount, newElement: newElement)
_endMutation()
}
/// Adds the elements of a sequence to the end of the array.
///
/// Use this method to append the elements of a sequence to the end of this
/// array. This example appends the elements of a `Range<Int>` instance
/// to an array of integers.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.append(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
///
/// - Parameter newElements: The elements to append to the array.
///
/// - Complexity: O(*m*) on average, where *m* is the length of
/// `newElements`, over many calls to `append(contentsOf:)` on the same
/// array.
@inlinable
@_semantics("array.append_contentsOf")
public mutating func append<S: Sequence>(contentsOf newElements: __owned S)
where S.Element == Element {
let newElementsCount = newElements.underestimatedCount
reserveCapacityForAppend(newElementsCount: newElementsCount)
_ = _buffer.beginCOWMutation()
let oldCount = self.count
let startNewElements = _buffer.firstElementAddress + oldCount
let buf = UnsafeMutableBufferPointer(
start: startNewElements,
count: self.capacity - oldCount)
let (remainder,writtenUpTo) = buf.initialize(from: newElements)
// trap on underflow from the sequence's underestimate:
let writtenCount = buf.distance(from: buf.startIndex, to: writtenUpTo)
_precondition(newElementsCount <= writtenCount,
"newElements.underestimatedCount was an overestimate")
// can't check for overflow as sequences can underestimate
// This check prevents a data race writing to _swiftEmptyArrayStorage
if writtenCount > 0 {
_buffer.count += writtenCount
}
if writtenUpTo == buf.endIndex {
// there may be elements that didn't fit in the existing buffer,
// append them in slow sequence-only mode
_buffer._arrayAppendSequence(IteratorSequence(remainder))
}
_endMutation()
}
@inlinable
@_semantics("array.reserve_capacity_for_append")
internal mutating func reserveCapacityForAppend(newElementsCount: Int) {
let oldCount = self.count
let oldCapacity = self.capacity
let newCount = oldCount + newElementsCount
// Ensure uniqueness, mutability, and sufficient storage. Note that
// for consistency, we need unique self even if newElements is empty.
self.reserveCapacity(
newCount > oldCapacity ?
Swift.max(newCount, _growArrayCapacity(oldCapacity))
: newCount)
}
@inlinable
public mutating func _customRemoveLast() -> Element? {
_precondition(count > 0, "Can't removeLast from an empty ArraySlice")
// FIXME(performance): if `self` is uniquely referenced, we should remove
// the element as shown below (this will deallocate the element and
// decrease memory use). If `self` is not uniquely referenced, the code
// below will make a copy of the storage, which is wasteful. Instead, we
// should just shrink the view without allocating new storage.
let i = endIndex
// We don't check for overflow in `i - 1` because `i` is known to be
// positive.
let result = self[i &- 1]
self.replaceSubrange((i &- 1)..<i, with: EmptyCollection())
return result
}
/// Removes and returns the element at the specified position.
///
/// All the elements following the specified position are moved up to
/// close the gap.
///
/// var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2]
/// let removed = measurements.remove(at: 2)
/// print(measurements)
/// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]"
///
/// - Parameter index: The position of the element to remove. `index` must
/// be a valid index of the array.
/// - Returns: The element at the specified index.
///
/// - Complexity: O(*n*), where *n* is the length of the array.
@inlinable
@discardableResult
public mutating func remove(at index: Int) -> Element {
let result = self[index]
self.replaceSubrange(index..<(index + 1), with: EmptyCollection())
return result
}
/// Inserts a new element at the specified position.
///
/// The new element is inserted before the element currently at the specified
/// index. If you pass the array's `endIndex` property as the `index`
/// parameter, the new element is appended to the array.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.insert(100, at: 3)
/// numbers.insert(200, at: numbers.endIndex)
///
/// print(numbers)
/// // Prints "[1, 2, 3, 100, 4, 5, 200]"
///
/// - Parameter newElement: The new element to insert into the array.
/// - Parameter i: The position at which to insert the new element.
/// `index` must be a valid index of the array or equal to its `endIndex`
/// property.
///
/// - Complexity: O(*n*), where *n* is the length of the array. If
/// `i == endIndex`, this method is equivalent to `append(_:)`.
@inlinable
public mutating func insert(_ newElement: __owned Element, at i: Int) {
_checkIndex(i)
self.replaceSubrange(i..<i, with: CollectionOfOne(newElement))
}
/// Removes all elements from the array.
///
/// - Parameter keepCapacity: Pass `true` to keep the existing capacity of
/// the array after removing its elements. The default value is
/// `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the array.
@inlinable
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
if !keepCapacity {
_buffer = _Buffer()
}
else {
self.replaceSubrange(indices, with: EmptyCollection())
}
}
//===--- algorithms -----------------------------------------------------===//
@inlinable
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
return try withUnsafeMutableBufferPointer {
(bufferPointer) -> R in
return try body(&bufferPointer)
}
}
@inlinable
public mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
return try withUnsafeMutableBufferPointer {
(bufferPointer) -> R in
return try body(&bufferPointer)
}
}
@inlinable
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
return try withUnsafeBufferPointer {
(bufferPointer) -> R in
return try body(bufferPointer)
}
}
@inlinable
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
if let n = _buffer.requestNativeBuffer() {
return ContiguousArray(_buffer: n)
}
return _copyCollectionToContiguousArray(self)
}
}
extension ArraySlice: CustomReflectable {
/// A mirror that reflects the array.
public var customMirror: Mirror {
return Mirror(
self,
unlabeledChildren: self,
displayStyle: .collection)
}
}
extension ArraySlice: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the array and its elements.
public var description: String {
return _makeCollectionDescription()
}
/// A textual representation of the array and its elements, suitable for
/// debugging.
public var debugDescription: String {
return _makeCollectionDescription(withTypeName: "ArraySlice")
}
}
extension ArraySlice {
@usableFromInline @_transparent
internal func _cPointerArgs() -> (AnyObject?, UnsafeRawPointer?) {
let p = _baseAddressIfContiguous
if _fastPath(p != nil || isEmpty) {
return (_owner, UnsafeRawPointer(p))
}
let n = ContiguousArray(self._buffer)._buffer
return (n.owner, UnsafeRawPointer(n.firstElementAddress))
}
}
extension ArraySlice {
/// Calls a closure with a pointer to the array's contiguous storage.
///
/// Often, the optimizer can eliminate bounds checks within an array
/// algorithm, but when that fails, invoking the same algorithm on the
/// buffer pointer passed into your closure lets you trade safety for speed.
///
/// The following example shows how you can iterate over the contents of the
/// buffer pointer:
///
/// let numbers = [1, 2, 3, 4, 5]
/// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in
/// var result = 0
/// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) {
/// result += buffer[i]
/// }
/// return result
/// }
/// // 'sum' == 9
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the
/// pointer for later use.
///
/// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that
/// points to the contiguous storage for the array. If
/// `body` has a return value, that value is also used as the return value
/// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is
/// valid only for the duration of the method's execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
return try _buffer.withUnsafeBufferPointer(body)
}
/// Calls the given closure with a pointer to the array's mutable contiguous
/// storage.
///
/// Often, the optimizer can eliminate bounds checks within an array
/// algorithm, but when that fails, invoking the same algorithm on the
/// buffer pointer passed into your closure lets you trade safety for speed.
///
/// The following example shows how modifying the contents of the
/// `UnsafeMutableBufferPointer` argument to `body` alters the contents of
/// the array:
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.withUnsafeMutableBufferPointer { buffer in
/// for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) {
/// buffer.swapAt(i, i + 1)
/// }
/// }
/// print(numbers)
/// // Prints "[2, 1, 4, 3, 5]"
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withUnsafeMutableBufferPointer(_:)`. Do not store or
/// return the pointer for later use.
///
/// - Warning: Do not rely on anything about the array that is the target of
/// this method during execution of the `body` closure; it might not
/// appear to have its correct value. Instead, use only the
/// `UnsafeMutableBufferPointer` argument to `body`.
///
/// - Parameter body: A closure with an `UnsafeMutableBufferPointer`
/// parameter that points to the contiguous storage for the array.
/// If `body` has a return value, that value is also
/// used as the return value for the `withUnsafeMutableBufferPointer(_:)`
/// method. The pointer argument is valid only for the duration of the
/// method's execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@_semantics("array.withUnsafeMutableBufferPointer")
@inlinable // FIXME(inline-always)
@inline(__always) // Performance: This method should get inlined into the
// caller such that we can combine the partial apply with the apply in this
// function saving on allocating a closure context. This becomes unnecessary
// once we allocate noescape closures on the stack.
public mutating func withUnsafeMutableBufferPointer<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {
let count = self.count
// Ensure unique storage
_makeMutableAndUnique()
// Ensure that body can't invalidate the storage or its bounds by
// moving self into a temporary working array.
// NOTE: The stack promotion optimization that keys of the
// "array.withUnsafeMutableBufferPointer" semantics annotation relies on the
// array buffer not being able to escape in the closure. It can do this
// because we swap the array buffer in self with an empty buffer here. Any
// escape via the address of self in the closure will therefore escape the
// empty array.
var work = ArraySlice()
(work, self) = (self, work)
// Create an UnsafeBufferPointer over work that we can pass to body
let pointer = work._buffer.firstElementAddress
var inoutBufferPointer = UnsafeMutableBufferPointer(
start: pointer, count: count)
// Put the working array back before returning.
defer {
_precondition(
inoutBufferPointer.baseAddress == pointer &&
inoutBufferPointer.count == count,
"ArraySlice withUnsafeMutableBufferPointer: replacing the buffer is not allowed")
(work, self) = (self, work)
_endMutation()
}
// Invoke the body.
return try body(&inoutBufferPointer)
}
@inlinable
public __consuming func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
guard !self.isEmpty else { return (makeIterator(),buffer.startIndex) }
// It is not OK for there to be no pointer/not enough space, as this is
// a precondition and Array never lies about its count.
guard var p = buffer.baseAddress
else { _preconditionFailure("Attempt to copy contents into nil buffer pointer") }
_precondition(self.count <= buffer.count,
"Insufficient space allocated to copy array contents")
if let s = _baseAddressIfContiguous {
p.initialize(from: s, count: self.count)
// Need a _fixLifetime bracketing the _baseAddressIfContiguous getter
// and all uses of the pointer it returns:
_fixLifetime(self._owner)
} else {
for x in self {
p.initialize(to: x)
p += 1
}
}
var it = IndexingIterator(_elements: self)
it._position = endIndex
return (it,buffer.index(buffer.startIndex, offsetBy: self.count))
}
}
extension ArraySlice {
/// Replaces a range of elements with the elements in the specified
/// collection.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting the new elements at the same location. The
/// number of new elements need not match the number of elements being
/// removed.
///
/// In this example, three elements in the middle of an array of integers are
/// replaced by the five elements of a `Repeated<Int>` instance.
///
/// var nums = [10, 20, 30, 40, 50]
/// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
/// print(nums)
/// // Prints "[10, 1, 1, 1, 1, 1, 50]"
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.startIndex`. Calling
/// the `insert(contentsOf:at:)` method instead is preferred.
///
/// Likewise, if you pass a zero-length collection as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The start and end of
/// a subrange must be valid indices of the array.
/// - newElements: The new elements to add to the array.
///
/// - Complexity: O(*n* + *m*), where *n* is length of the array and
/// *m* is the length of `newElements`. If the call to this method simply
/// appends the contents of `newElements` to the array, this method is
/// equivalent to `append(contentsOf:)`.
@inlinable
@_semantics("array.mutate_unknown")
public mutating func replaceSubrange<C>(
_ subrange: Range<Int>,
with newElements: __owned C
) where C: Collection, C.Element == Element {
_precondition(subrange.lowerBound >= _buffer.startIndex,
"ArraySlice replace: subrange start is before the startIndex")
_precondition(subrange.upperBound <= _buffer.endIndex,
"ArraySlice replace: subrange extends past the end")
let oldCount = _buffer.count
let eraseCount = subrange.count
let insertCount = newElements.count
let growth = insertCount - eraseCount
if _buffer.beginCOWMutation() && _buffer.capacity >= oldCount + growth {
_buffer.replaceSubrange(
subrange, with: insertCount, elementsOf: newElements)
} else {
_buffer._arrayOutOfPlaceReplace(subrange, with: newElements, count: insertCount)
}
_endMutation()
}
}
extension ArraySlice: Equatable where Element: Equatable {
/// Returns a Boolean value indicating whether two arrays contain the same
/// elements in the same order.
///
/// You can use the equal-to operator (`==`) to compare any two arrays
/// that store the same, `Equatable`-conforming element type.
///
/// - Parameters:
/// - lhs: An array to compare.
/// - rhs: Another array to compare.
@inlinable
public static func ==(lhs: ArraySlice<Element>, rhs: ArraySlice<Element>) -> Bool {
let lhsCount = lhs.count
if lhsCount != rhs.count {
return false
}
// Test referential equality.
if lhsCount == 0 || lhs._buffer.identity == rhs._buffer.identity {
return true
}
var streamLHS = lhs.makeIterator()
var streamRHS = rhs.makeIterator()
var nextLHS = streamLHS.next()
while nextLHS != nil {
let nextRHS = streamRHS.next()
if nextLHS != nextRHS {
return false
}
nextLHS = streamLHS.next()
}
return true
}
}
extension ArraySlice: Hashable where Element: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(count) // discriminator
for element in self {
hasher.combine(element)
}
}
}
extension ArraySlice {
/// Calls the given closure with a pointer to the underlying bytes of the
/// array's mutable contiguous storage.
///
/// The array's `Element` type must be a *trivial type*, which can be copied
/// with just a bit-for-bit copy without any indirection or
/// reference-counting operations. Generally, native Swift types that do not
/// contain strong or weak references are trivial, as are imported C structs
/// and enums.
///
/// The following example copies bytes from the `byteValues` array into
/// `numbers`, an array of `Int32`:
///
/// var numbers: [Int32] = [0, 0]
/// var byteValues: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00]
///
/// numbers.withUnsafeMutableBytes { destBytes in
/// byteValues.withUnsafeBytes { srcBytes in
/// destBytes.copyBytes(from: srcBytes)
/// }
/// }
/// // numbers == [1, 2]
///
/// - Note: This example shows the behavior on a little-endian platform.
///
/// The pointer passed as an argument to `body` is valid only for the
/// lifetime of the closure. Do not escape it from the closure for later
/// use.
///
/// - Warning: Do not rely on anything about the array that is the target of
/// this method during execution of the `body` closure; it might not
/// appear to have its correct value. Instead, use only the
/// `UnsafeMutableRawBufferPointer` argument to `body`.
///
/// - Parameter body: A closure with an `UnsafeMutableRawBufferPointer`
/// parameter that points to the contiguous storage for the array.
/// If no such storage exists, it is created. If `body` has a return value, that value is also
/// used as the return value for the `withUnsafeMutableBytes(_:)` method.
/// The argument is valid only for the duration of the closure's
/// execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public mutating func withUnsafeMutableBytes<R>(
_ body: (UnsafeMutableRawBufferPointer) throws -> R
) rethrows -> R {
return try self.withUnsafeMutableBufferPointer {
return try body(UnsafeMutableRawBufferPointer($0))
}
}
/// Calls the given closure with a pointer to the underlying bytes of the
/// array's contiguous storage.
///
/// The array's `Element` type must be a *trivial type*, which can be copied
/// with just a bit-for-bit copy without any indirection or
/// reference-counting operations. Generally, native Swift types that do not
/// contain strong or weak references are trivial, as are imported C structs
/// and enums.
///
/// The following example copies the bytes of the `numbers` array into a
/// buffer of `UInt8`:
///
/// var numbers: [Int32] = [1, 2, 3]
/// var byteBuffer: [UInt8] = []
/// numbers.withUnsafeBytes {
/// byteBuffer.append(contentsOf: $0)
/// }
/// // byteBuffer == [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]
///
/// - Note: This example shows the behavior on a little-endian platform.
///
/// - Parameter body: A closure with an `UnsafeRawBufferPointer` parameter
/// that points to the contiguous storage for the array.
/// If no such storage exists, it is created. If `body` has a return value, that value is also
/// used as the return value for the `withUnsafeBytes(_:)` method. The
/// argument is valid only for the duration of the closure's execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public func withUnsafeBytes<R>(
_ body: (UnsafeRawBufferPointer) throws -> R
) rethrows -> R {
return try self.withUnsafeBufferPointer {
try body(UnsafeRawBufferPointer($0))
}
}
}
extension ArraySlice {
@inlinable
public // @testable
init(_startIndex: Int) {
self.init(
_buffer: _Buffer(
_buffer: ContiguousArray()._buffer,
shiftedToStartIndex: _startIndex))
}
}
| apache-2.0 |
UsabilityEtc/nscolor-components | Sources/NSColor+Components.swift | 1 | 2528 | //
// NSColor+Components.swift
// NSColorComponents
//
// Created by Jeffrey Morgan on 28/02/2016.
// Copyright © 2016 Jeffrey Morgan under the MIT License.
//
import Cocoa
public extension NSColor {
/**
A tuple of the red, green, blue and alpha components of this NSColor calibrated
in the RGB color space. Each tuple value is a CGFloat between 0 and 1.
*/
var CGFloatRGB: (red:CGFloat, green:CGFloat, blue:CGFloat, alpha:CGFloat)? {
if let calibratedColor = colorUsingColorSpaceName(NSCalibratedRGBColorSpace) {
var redComponent: CGFloat = 0
var greenComponent: CGFloat = 0
var blueComponent: CGFloat = 0
var alphaComponent: CGFloat = 0
calibratedColor.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha: &alphaComponent)
return (redComponent, greenComponent, blueComponent, alphaComponent)
}
return nil
}
/**
A tuple of the red, green, blue and alpha components of this NSColor calibrated
in the RGB color space. Each tuple value is an Int between 0 and 255.
*/
var IntRGB: (red:Int, green:Int, blue:Int, alpha:Int)? {
if let (red, green, blue, alpha) = CGFloatRGB {
return (Int(red*255), Int(green*255), Int(blue*255), Int(alpha*255))
}
return nil
}
}
public extension NSColor {
/**
A tuple of the hue, saturation, brightness and alpha components of this NSColor
calibrated in the RGB color space. Each tuple value is a CGFloat between 0 and 1.
*/
var CGFloatHSB: (hue:CGFloat, saturation:CGFloat, brightness:CGFloat, alpha:CGFloat)? {
if let calibratedColor = colorUsingColorSpaceName(NSCalibratedRGBColorSpace) {
var hueComponent: CGFloat = 0
var saturationComponent: CGFloat = 0
var brightnessComponent: CGFloat = 0
var alphaFloatValue: CGFloat = 0
calibratedColor.getHue(&hueComponent, saturation: &saturationComponent, brightness: &brightnessComponent, alpha: &alphaFloatValue)
return (hueComponent, saturationComponent, brightnessComponent, alphaFloatValue)
}
return nil
}
/**
A tuple of the hue, saturation, brightness and alpha components of this NSColor
calibrated in the RGB color space. Each tuple value is an Int between 0 and 255.
*/
var IntHSB: (hue:Int, saturation:Int, brightness:Int, alpha:Int)? {
if let (hue, saturation, brightness, alpha) = CGFloatHSB {
return (Int(hue*255), Int(saturation*255), Int(brightness*255), Int(alpha*255))
}
return nil
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/ScreenNavigationModel.swift | 1 | 992 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public struct ScreenNavigationModel {
public let leadingButton: Screen.Style.LeadingButton
public let trailingButton: Screen.Style.TrailingButton
public let barStyle: Screen.Style.Bar
public let titleViewStyle: Screen.Style.TitleView
public init(
leadingButton: Screen.Style.LeadingButton,
trailingButton: Screen.Style.TrailingButton,
titleViewStyle: Screen.Style.TitleView,
barStyle: Screen.Style.Bar
) {
self.leadingButton = leadingButton
self.trailingButton = trailingButton
self.titleViewStyle = titleViewStyle
self.barStyle = barStyle
}
}
extension ScreenNavigationModel {
public static let noneDark = ScreenNavigationModel(
leadingButton: .none,
trailingButton: .none,
titleViewStyle: .none,
barStyle: .darkContent()
)
}
extension ScreenNavigationModel: Equatable {}
| lgpl-3.0 |
randallli/material-components-ios | components/Cards/tests/unit/MDCCardColorThemerTests.swift | 1 | 1538 | /*
Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
import MaterialComponents.MaterialCards
import MaterialComponents.MaterialCards_ColorThemer
class CardColorThemerTests: XCTestCase {
func testCardColorThemer() {
// Given
let colorScheme = MDCSemanticColorScheme()
let card = MDCCard()
colorScheme.surfaceColor = .red
card.backgroundColor = .white
// When
MDCCardsColorThemer.applySemanticColorScheme(colorScheme, to: card)
// Then
XCTAssertEqual(card.backgroundColor, colorScheme.surfaceColor)
}
func testCardCollectionCellColorThemer() {
// Given
let colorScheme = MDCSemanticColorScheme()
let cardCell = MDCCardCollectionCell()
colorScheme.surfaceColor = .red
cardCell.backgroundColor = .white
// When
MDCCardsColorThemer.applySemanticColorScheme(colorScheme, toCardCell: cardCell)
// Then
XCTAssertEqual(cardCell.backgroundColor, colorScheme.surfaceColor)
}
}
| apache-2.0 |
natecook1000/swift | test/SILGen/objc_bridging_nsstring.swift | 9 | 430 | // RUN: %empty-directory(%t)
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle %s -enable-sil-ownership
// REQUIRES: objc_interop
import Foundation
extension NSString {
var x: Float { return 0.0 }
}
// note: this has to be a var
var str: String = "hello world"
// Crash when NSString member is accessed on a String with an lvalue base
_ = str.x
| apache-2.0 |
Poligun/NihonngoSwift | Nihonngo/LoadingCell.swift | 1 | 1621 | //
// LoadingCell.swift
// Nihonngo
//
// Created by ZhaoYuhan on 15/1/13.
// Copyright (c) 2015年 ZhaoYuhan. All rights reserved.
//
import UIKit
class LoadingCell: BaseCell {
private let label = UILabel()
private let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
override class var defaultReuseIdentifier: String {
return "LoadingCell"
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
label.font = UIFont.systemFontOfSize(15.0)
label.textColor = UIColor.blackColor()
label.textAlignment = .Center
self.contentView.addSubview(label)
indicator.setTranslatesAutoresizingMaskIntoConstraints(false)
indicator.startAnimating()
self.contentView.addSubview(indicator)
self.contentView.addConstraints(NSLayoutConstraint.constraints(
views: ["label": label, "indicator": indicator],
formats: "V:|-8-[label]-8-|",
"V:|-8-[indicator]-8-|",
"H:|-8-[label]-8-|",
"H:[indicator]-8-|"))
}
func setLoadingText(text: String, animating: Bool) {
label.text = text
if animating {
indicator.startAnimating()
} else {
indicator.stopAnimating()
}
}
}
| mit |
zdima/ZDMatrixPopover | src/ZDMatrixPopover.swift | 1 | 3337 | //
// ZDMatrixPopover.swift
// ZDMatrixPopover
//
// Created by Dmitriy Zakharkin on 1/7/17.
// Copyright © 2017 Dmitriy Zakharkin. All rights reserved.
//
import Cocoa
@objc public protocol ZDMatrixPopoverDelegate {
/// getColumnFormatter return an optional Formatter object to be use for specified column.
/// This method is called when popup is constructed first time or when data size has changed since last call.
/// This method can return nil if there is no formatter to be used.
/// When attributedString is called, the withDefaultAttributes include following information:
/// "column" : NSNumber()
/// "row" : NSNumber
/// "alignment" : NSTextAlignment
func getColumnFormatter(column: Int) -> Formatter?
/// getColumnAlignment return an optional alignment attribute for specified column.
/// This method is called when popup is constructed first time or when data size has changed since last call.
/// This method can return nil if there is no special aligment needed.
/// By default all count will be aligned to NSTextAlignment.left
func getColumnAlignment(column: Int) -> NSTextAlignment
/// getColumnWidth return width of the column.
/// The width will be calculated based on content when getColumnWidth return -1.
/// By default getColumnWidth will return -1.
func getColumnWidth(column: Int) -> Int
}
@objc(ZDMatrixPopover)
@IBDesignable public class ZDMatrixPopover: NSObject {
internal var controller: ZDMatrixPopoverController!
public required override init() {
super.init()
controller = ZDMatrixPopoverController(owner:self)
}
public override func prepareForInterfaceBuilder() {
titleFontSize = NSFont.systemFontSize(for: NSControlSize.regular)
}
/// Delegate object of type ZDMatrixPopoverDelegate
/// Due to storyboard limitation we have to use AnyObject as type to allow storyboard binding.
///
/// Interface Builder
///
/// Interface Builder does not support connecting to an outlet in a Swift file
/// when the outlet’s type is a protocol. Declare the outlet's type as AnyObject
/// or NSObject, connect objects to the outlet using Interface Builder, then change
/// the outlet's type back to the protocol. (17023935)
///
@IBOutlet public weak var delegate: AnyObject? {
set {
if let newDelegate = newValue as? ZDMatrixPopoverDelegate {
self.controller.m_delegate = newDelegate
}
}
get {
return self.controller.m_delegate
}
}
@IBInspectable public var titleFontSize: CGFloat = NSFont.systemFontSize(for: NSControlSize.regular)
@IBInspectable public var dataFontSize: CGFloat = NSFont.systemFontSize(for: NSControlSize.regular)
public func show(
data: [[Any]],
title: String,
relativeTo rect: NSRect,
of view: NSView,
preferredEdge: NSRectEdge) throws {
try controller.show(data: data, title: title, relativeTo: rect, of: view, preferredEdge: preferredEdge)
}
public func close() throws {
try controller.close()
}
public private(set) var isShown: Bool {
get {
return controller.isShown
}
set {
}
}
}
| mit |
CocoaHeadsCR/CETAV_Mapa | CETAV/AppDelegate.swift | 1 | 2084 | //
// AppDelegate.swift
// CETAV
//
// Created by Esteban Torres on 12/2/16.
// Copyright © 2016 Esteban Torres. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
cwwise/CWWeChat | CWWeChat/Expand/Tool/ChatTimeTool.swift | 2 | 3305 | //
// ChatTimeTool.swift
// CWWeChat
//
// Created by chenwei on 16/4/8.
// Copyright © 2016年 chenwei. All rights reserved.
//
import UIKit
let KTimeFormate:String = "yyyy-MM-dd HH:mm:ss:SSS"
let KMessageTimeFormate:String = "yyyy-MM-dd'T'HH:mm:ss'Z'"
class ChatTimeTool: NSObject {
static let shareChatTimeTool = ChatTimeTool()
var formatter:DateFormatter = {
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
return formatter
}()
fileprivate override init() {
super.init()
}
internal class func stringFromDate(_ date: Date) -> String {
let formatter = shareChatTimeTool.formatter
//格式化时间
formatter.dateFormat = KTimeFormate
let dateString = formatter.string(from: date)
return dateString
}
internal class func dateFromString(_ dateString: String, formatter string: String) -> Date {
let formatter = shareChatTimeTool.formatter
//格式化时间
formatter.dateFormat = string
let date = formatter.date(from: dateString)
if date == nil {
return Date()
}
return date!
}
internal class func stringFromDateString(_ dateString: String, fromDateFormat: String = KMessageTimeFormate, toDateFormat: String = KTimeFormate) -> String? {
let formatter = shareChatTimeTool.formatter
//格式化时间
formatter.dateFormat = fromDateFormat
let date = formatter.date(from: dateString)
if (date == nil) {
return nil
}
//转换成当前格式的string
formatter.dateFormat = toDateFormat
let dateString = formatter.string(from: date!)
return dateString
}
internal class func stringFromDateTimeInterval(_ timeInterval: TimeInterval) -> String {
let date = Date(timeIntervalSince1970: timeInterval)
return self.stringFromDate(date)
}
internal class func timeStringFromSinceDate(_ date: Date) -> String {
//当前时间和消息时间
let nowDate = Date()
let messageDate = date
let dateFormatter = shareChatTimeTool.formatter
dateFormatter.dateFormat = "yyyy-MM-dd"
let theDay = dateFormatter.string(from: messageDate)
let currentDay = dateFormatter.string(from: nowDate)
//当天
if theDay == currentDay {
dateFormatter.dateFormat = "ah:mm"
return dateFormatter.string(from: messageDate)
}
//昨天
else if (dateFormatter.date(from: currentDay)?.timeIntervalSince(dateFormatter.date(from: theDay)!) == 86400) {
dateFormatter.dateFormat = "ah:mm"
return "昨天 \(dateFormatter.string(from: messageDate))"
}
//一周
else if (dateFormatter.date(from: currentDay)?.timeIntervalSince(dateFormatter.date(from: theDay)!) == 86400 * 7) {
dateFormatter.dateFormat = "EEEE ah:mm"
return dateFormatter.string(from: messageDate)
}
//一周之前
else {
dateFormatter.dateFormat = "yyyy-MM-dd ah:mm"
return dateFormatter.string(from: messageDate)
}
}
}
| mit |
gavi/swiftcsv | main.swift | 1 | 569 | //
// main.swift
// CSV
//
// Created by Gavi Narra on 5/2/15.
// Copyright (c) 2015 ObjectGraph LLC. All rights reserved.
//
import Foundation
func Test1(){
let file="/Users/gavi/work/mac/CSV/CSV/test_files/excel_csv.csv"
let dictReader=DictReader(file:file,firstRowColNames:true,dialect:Dialect.Excel)
print(dictReader.colNames)
while(true){
if let x=dictReader.readLine(){
print(x)
}else{
break
}
}
for dict in dictReader{
print(dict)
}
}
print(Dialect.Excel)
//Test1()
| mit |
bradleypj823/ParseAndCoreImage | ParseCoreImage/GalleryViewController.swift | 1 | 3070 | //
// GalleryViewController.swift
// ParseCoreImage
//
// Created by Bradley Johnson on 3/5/15.
// Copyright (c) 2015 BPJ. All rights reserved.
//
import UIKit
import Photos
protocol GalleryDelegate: class {
func userDidSelectImage(image : UIImage)
}
class GalleryViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collectionView: UICollectionView!
weak var delegate : GalleryDelegate!
var scale : CGFloat = 1.0
//photos framework properties
var assetsFetchResults : PHFetchResult!
var assetCollection : PHAssetCollection!
var imageManager = PHCachingImageManager()
var destinationImageSize : CGSize!
var flowLayout : UICollectionViewFlowLayout!
override func viewDidLoad() {
super.viewDidLoad()
self.imageManager = PHCachingImageManager()
self.assetsFetchResults = PHAsset.fetchAssetsWithOptions(nil)
self.collectionView.dataSource = self
self.collectionView.delegate = self
let pinch = UIPinchGestureRecognizer(target: self, action: "pinchRecognized:")
self.collectionView.addGestureRecognizer(pinch)
self.flowLayout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
// Do any additional setup after loading the view.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.assetsFetchResults.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("GalleryCell", forIndexPath: indexPath) as! GalleryCell
let asset = self.assetsFetchResults[indexPath.row] as! PHAsset
self.imageManager.requestImageForAsset(asset, targetSize: self.flowLayout.itemSize, contentMode: PHImageContentMode.AspectFill, options: nil) { (requestedImage, info) -> Void in
cell.imageView.image = requestedImage
}
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(75 * self.scale, 75 * self.scale)
}
func pinchRecognized(sender : UIPinchGestureRecognizer) {
if sender.state == UIGestureRecognizerState.Changed {
self.scale = sender.scale
self.collectionView.collectionViewLayout.invalidateLayout()
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let asset = self.assetsFetchResults[indexPath.row] as! PHAsset
self.imageManager.requestImageForAsset(asset, targetSize: CGSize(width: 300, height: 400), contentMode: PHImageContentMode.AspectFill, options: nil) { (requestedImage, info) -> Void in
self.delegate?.userDidSelectImage(requestedImage)
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
}
| mit |
bvic23/VinceRP | VinceRP/Common/Util/WeakSet.swift | 1 | 1668 | //
// Created by Viktor Belenyesi on 18/04/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
// https://github.com/scala/scala/blob/2.11.x/src/library/scala/ref/WeakReference.scala
class WeakReference<T: AnyObject where T: Hashable>: Hashable {
weak var value: T?
init(_ value: T) {
self.value = value
}
var hashValue: Int {
guard let v = self.value else {
return 0
}
return v.hashValue
}
}
func ==<T>(lhs: WeakReference<T>, rhs: WeakReference<T>) -> Bool {
return lhs.hashValue == rhs.hashValue
}
public class WeakSet<T: Hashable where T: AnyObject> {
private var _array: [WeakReference<T>]
public init() {
_array = Array()
}
public init(_ array: [T]) {
_array = array.map {
WeakReference($0)
}
}
public var set: Set<T> {
return Set(self.array())
}
public func insert(member: T) {
for e in _array {
if e.hashValue == member.hashValue {
return
}
}
_array.append(WeakReference(member))
}
public func filter(@noescape includeElement: (T) -> Bool) -> WeakSet<T> {
return WeakSet(self.array().filter(includeElement))
}
public func hasElementPassingTest(@noescape filterFunc: (T) -> Bool) -> Bool {
return self.array().hasElementPassingTest(filterFunc)
}
private func array() -> Array<T> {
var result = Array<T>()
for item in _array {
if let v = item.value {
result.append(v)
}
}
return result
}
}
| mit |
lorentey/swift | validation-test/compiler_crashers_fixed/01528-getselftypeforcontainer.swift | 65 | 595 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
lass func i: a {
class A<c) {
var _ = b: a {
let foo as Boolean, e? = B<() -> Int = ")
self)?) {
protocol P {
}
switch x in x in x }
protocol b {
typealias d: d : B<1 {
}
convenience init() ->Bool
| apache-2.0 |
LFL2018/swiftSmpleCode | RxSwiftDemo/RxSwiftDemo/ViewController.swift | 1 | 2091 | //
// ViewController.swift
// RxSwiftDemo
//
// Created by DragonLi on 2017/8/31.
// Copyright © 2017年 XiTu Inc. All rights reserved.
//
import UIKit
private let cellIDString = "cellIDString"
class ViewController: UIViewController {
lazy var sourceDatas : [String] = {
let sourceDatas = ["UIBaseUserPartOne"]
return sourceDatas
}()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "RxSwiftDemo"
view.backgroundColor = UIColor.gray
tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: cellIDString)
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
}
}
// MARK: - Delegate
extension ViewController:UITableViewDataSource,UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return sourceDatas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: cellIDString, for: indexPath)
cell.textLabel?.text = "\(sourceDatas[indexPath.row])"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(#function)
pushToVC(stringVC: sourceDatas[indexPath.row])
}
}
// MARK: - handle push VC
extension ViewController {
fileprivate func pushToVC(stringVC:String){
guard let nameSpace = Bundle.main.infoDictionary!["CFBundleName"] as? String else {
return
}
guard let VC_Class = NSClassFromString(nameSpace + "." + stringVC) else {
return
}
guard let VC_Type = VC_Class as? UIViewController.Type else {
return
}
let pushVC = VC_Type.init()
pushVC.view.backgroundColor = UIColor.white
self.navigationController!.pushViewController(pushVC, animated: true)
}
}
| mit |
bppr/Swiftest | src/Swiftest/Client/ExpectationDSL.swift | 1 | 1759 | private func __add<T:Expectable>(ex: T) -> T {
context.currentExample.addExpectation(ex.result)
return ex
}
public func expect<T:Equatable>(
subject: [T]?,
file: String = #file,
line: UInt = #line
) -> ArrayExpectation<T> {
return __add(
ArrayExpectation(subject: subject, cursor: Cursor(file: file, line: line))
)
}
public func expect<K:Hashable,V:Equatable>(
subject: [K:V],
file: String = #file,
line: UInt = #line
) -> DictionaryExpectation<K, V> {
return __add(
DictionaryExpectation(subject: subject, cursor: Cursor(file: file, line: line))
)
}
public func expect<T:Equatable>(
subject: T?,
file: String = #file,
line: UInt = #line
) -> Expectation<T, EquatableMatcher<T>> {
return __add(
Expectation(subject: subject, cursor: Cursor(file: file, line: line))
)
}
public func expect<T:Comparable>(
subject: T?,
file: String = #file,
line: UInt = #line
) -> Expectation<T, ComparableMatcher<T>> {
return __add(
Expectation(subject: subject, cursor: Cursor(file: file, line: line))
)
}
public func expect(
file: String = #file,
line: UInt = #line,
subject: Void throws -> Void
) -> Expectation<Void throws -> Void, ThrowableVoidMatcher> {
return __add(
Expectation(subject: subject, cursor: Cursor(file: file, line: line))
)
}
public func expect(
file: String = #file,
line: UInt = #line,
subject: VoidBlk?
) -> Expectation<VoidBlk, VoidMatcher> {
return __add(
Expectation(subject: subject, cursor: Cursor(file: file, line: line))
)
}
public func expect(
subject: String?,
file: String = #file,
line: UInt = #line
) -> Expectation<String, StringMatcher> {
return __add(
Expectation(subject: subject, cursor: Cursor(file: file, line: line))
)
}
| mit |
MidnightPulse/Tabman | Carthage/Checkouts/Pageboy/Package.swift | 1 | 109 | import PackageDescription
let package = Package(
name: "Pageboy",
exclude: ["Example", "Artwork"]
)
| mit |
hirohitokato/DetailScrubber | DetailScrubber/MovieSlider.swift | 1 | 12395 | //
// MovieSlider.swift
//
// Copyright (c) 2017 Hirohito Kato. MIT License.
//
import UIKit
import QuartzCore
public enum StackState {
case inactive
case active
var stackColor: UIColor {
switch self {
case .inactive: return .black
case .active: return .darkGray
}
}
}
private struct Stack {
let view: UIView
var state: StackState
}
@objc public protocol MovieSliderDelegate {
/**
Called whenever the slider's current stack changes.
This is called when a stack mode is on. It's optinal method.
- parameter slider: An object representing the movie slider notifying this information.
- parameter index: The stack index starts from 0(most left side)
*/
func movieSlider(_ slider: MovieSlider, didChangeStackIndex index:Int)
}
extension MovieSliderDelegate {
func movieSlider(_ slider: MovieSlider, didChangeStackIndex index:Int) {}
}
open class MovieSlider : DetailScrubber {
private let kThumbImageSize : CGFloat = 20.0
private let kThumbImageMargin : CGFloat = 10.0
private let kThumbSize : CGFloat = 15.0
private let kTrackHeight : CGFloat = 3.0
private let kFrameGap: CGFloat = 2
private var kFrameHeight: CGFloat {
return minimumTrackImage(for: UIControl.State())!.size.height
}
public var stackMode: Bool = false {
didSet {
if stackMode != oldValue {
showStacks(stackMode)
_index = currentIndex
if stackMode {
_value = value
setValue(0.5, animated: true)
} else {
setValue(_value, animated: true)
}
}
}
}
private var _stacks = [Stack]()
private var _index: Int = 0
private var _value: Float = 0.0
public var numberOfStacks = 30 {
didSet {
guard stackMode == false else {
print("Cannot change number of stacks during stack mode.")
numberOfStacks = oldValue
return
}
}
}
public weak var movieSliderDelegate: MovieSliderDelegate? = nil
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_setupStacking()
_setupAppearance()
_value = value
}
override public init(frame: CGRect) {
super.init(frame: frame)
_setupStacking()
_setupAppearance()
_value = value
}
}
private typealias MovieSlider_Appearance = MovieSlider
private extension MovieSlider_Appearance {
func _setupAppearance() {
tintColor = UIColor.white
// thumb image
setThumbImage(_imageForThumb(), for: UIControl.State())
// track image
let tracks = _imagesForTrack()
setMinimumTrackImage(tracks.minImage, for: UIControl.State())
setMaximumTrackImage(tracks.maxImage, for: UIControl.State())
}
func _imageForThumb() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(
CGSize(width: kThumbImageSize,
height: kThumbImageSize+kThumbImageMargin*3.0), false, 2.0)
defer { UIGraphicsEndImageContext() }
let ctx = UIGraphicsGetCurrentContext()
ctx!.setFillColor(UIColor.white.cgColor)
ctx!.setLineWidth(0.25)
ctx!.addEllipse(in: CGRect(x: (kThumbImageSize-kThumbSize)/2.0,
y: (kThumbImageSize+kThumbSize)/2.0,
width: kThumbSize, height: kThumbSize))
let shadowColor = UIColor.darkGray.cgColor
let shadowOffset = CGSize(width: 0, height: 0.5)
let shadowBlur : CGFloat = 1.0
ctx!.setShadow(offset: shadowOffset, blur: shadowBlur, color: shadowColor);
ctx!.drawPath(using: .fill)
return UIGraphicsGetImageFromCurrentImageContext()
}
func _imagesForTrack() -> (minImage: UIImage, maxImage: UIImage) {
let minTrack: UIImage
let maxTrack: UIImage
// minimum track image
do {
UIGraphicsBeginImageContextWithOptions(
CGSize(width: kTrackHeight, height: kTrackHeight), false, 2.0)
defer { UIGraphicsEndImageContext() }
let ctx = UIGraphicsGetCurrentContext()
ctx!.setFillColor(UIColor.white.cgColor)
ctx!.setLineWidth(0.25)
ctx!.addArc(center: CGPoint(x:kTrackHeight/2, y:kTrackHeight/2), radius: kTrackHeight/2,
startAngle: _DEG2RAD(90), endAngle: _DEG2RAD(270), clockwise: false)
ctx!.addLine(to: CGPoint(x: kTrackHeight, y: 0))
ctx!.addLine(to: CGPoint(x: kTrackHeight, y: kTrackHeight))
ctx!.addLine(to: CGPoint(x: kTrackHeight/2, y: kTrackHeight))
ctx!.closePath()
ctx!.drawPath(using: .fillStroke)
let tmpImage = UIGraphicsGetImageFromCurrentImageContext()
minTrack = tmpImage!.resizableImage(
withCapInsets: UIEdgeInsets(top: 1, left: kTrackHeight/2, bottom: 1, right: 1),
resizingMode: .tile)
}
// maximum track image
do {
UIGraphicsBeginImageContextWithOptions(
CGSize(width: kTrackHeight, height: kTrackHeight), false, 2.0)
defer { UIGraphicsEndImageContext() }
let ctx = UIGraphicsGetCurrentContext()
ctx!.setFillColor(UIColor.black.cgColor)
ctx!.addArc(center: CGPoint(x:kTrackHeight/2, y:kTrackHeight/2), radius: kTrackHeight/2,
startAngle: _DEG2RAD(90), endAngle: _DEG2RAD(270), clockwise: true)
ctx!.addLine(to: CGPoint(x: 0, y: 0))
ctx!.addLine(to: CGPoint(x: 0, y: kTrackHeight))
ctx!.addLine(to: CGPoint(x: kTrackHeight/2, y: kTrackHeight))
ctx!.closePath()
ctx!.drawPath(using: .fill)
let tmpImage = UIGraphicsGetImageFromCurrentImageContext()
maxTrack = tmpImage!.resizableImage(
withCapInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: kTrackHeight/2),
resizingMode: .tile)
}
return (minTrack, maxTrack)
}
}
private typealias MovieSlider_UISliderMethods = MovieSlider
extension MovieSlider_UISliderMethods {
open override func trackRect(forBounds bounds: CGRect) -> CGRect {
var rect = CGRect.zero
let dx : CGFloat = 2.0
rect.origin.x = bounds.origin.x + dx
rect.origin.y = bounds.origin.y + (bounds.size.height - kTrackHeight) / 2.0
rect.size.width = bounds.size.width - (dx * 2.0)
rect.size.height = kTrackHeight
return rect
}
open override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
var thumbRect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
let thumbCenter = CGPoint(x: thumbRect.midX, y: thumbRect.midY)
thumbRect.origin.x = thumbCenter.x - thumbRect.size.width/2;
thumbRect.origin.y = thumbCenter.y - thumbRect.size.height/2;
return thumbRect
}
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let view = super.hitTest(point, with: event)
if view == self {
// Only handle the point is on the thumb rect
let trackRect = self.trackRect(forBounds: bounds)
var thumbRect = self.thumbRect(forBounds: bounds, trackRect:trackRect, value:value)
// The area of handle point is greater than the size of thumb
thumbRect.origin.x -= thumbRect.size.width
thumbRect.size.width += 2 * thumbRect.size.width
if !thumbRect.contains(point) {
return nil
}
}
return view
}
}
// MARK: - Long Press Event
private typealias MovieSlider_StackingMode = MovieSlider
extension MovieSlider_StackingMode {
fileprivate func _setupStacking() {
}
fileprivate func showStacks(_ isOn: Bool) {
if !isOn {
_stacks.forEach{ $0.view.removeFromSuperview() }
_stacks.removeAll()
UIView.animate(withDuration: 0.15, animations: {
self.subviews[0].alpha = 1.0
self.subviews[1].alpha = 1.0
})
return
}
(0..<numberOfStacks).forEach { _ in
let state = StackState.inactive
let v = UIView(frame: CGRect.zero)
v.backgroundColor = state.stackColor
v.layer.borderWidth = 0.5
v.layer.borderColor = UIColor.lightGray.cgColor
let stack = Stack(view: v, state: state)
_stacks.append(stack)
}
let thumbImage = self.thumbImage(for: UIControl.State())
let minTrackIndex = subviews.firstIndex { v -> Bool in
if let imageView = v as? UIImageView {
return imageView.image == thumbImage
} else {
return false
}
}
let trackRect = self.trackRect(forBounds: bounds)
let thumbRect = self.thumbRect(forBounds: bounds, trackRect:trackRect, value:value)
var x: CGFloat = thumbRect.midX
let y: CGFloat = (frame.height-kFrameHeight)/2
let width: CGFloat = (frame.width - kFrameGap*(CGFloat(numberOfStacks-1))) / CGFloat(numberOfStacks)
let height: CGFloat = kFrameHeight
_stacks.forEach{
insertSubview($0.view, at: minTrackIndex!)
$0.view.frame = CGRect(x: x, y: y, width: width, height: height)
}
x = 0.0
UIView.animate(withDuration: 0.2, animations: {
self.subviews[0].alpha = 0.0
self.subviews[1].alpha = 0.0
self._stacks.forEach {
$0.view.frame = CGRect(x: x, y: y, width: width, height: height)
x += width + self.kFrameGap
}
})
updateStack()
}
open var currentIndex: Int {
get {
guard stackMode == true else { return -1 }
let valueRange = maximumValue - minimumValue
let range = Int(((value - minimumValue)/valueRange) * Float(numberOfStacks))
let currentIndex = min(range, numberOfStacks-1)
return currentIndex
}
set {
guard stackMode == true else { return }
let valueRange = maximumValue - minimumValue
value = (valueRange / Float(numberOfStacks * 2)) * (Float(newValue) * 2 + 1) + minimumValue
}
}
open func setStackState(_ state: StackState, at index: Int) {
guard index >= 0 && index < numberOfStacks else {
print("invalid index\(index) is set")
return
}
_stacks[index].state = state
updateStack()
}
fileprivate func updateStack() {
if stackMode {
for (i, stack) in _stacks.enumerated() {
stack.view.backgroundColor =
(i == currentIndex) ? .white : stack.state.stackColor
}
}
}
open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let beginTracking = super.beginTracking(touch, with: event)
notifyIndexIfNeeded()
updateStack()
return beginTracking
}
open override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let continueTracking = super.continueTracking(touch, with: event)
notifyIndexIfNeeded()
updateStack()
return continueTracking
}
open override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with: event)
notifyIndexIfNeeded()
updateStack()
}
open override func sendActions(for controlEvents: UIControl.Event) {
if !stackMode {
super.sendActions(for: controlEvents)
}
}
fileprivate func notifyIndexIfNeeded() {
if stackMode && _index != currentIndex {
_index = currentIndex
movieSliderDelegate?.movieSlider(self, didChangeStackIndex: currentIndex)
}
}
}
private func _DEG2RAD(_ deg: CGFloat) -> CGFloat {
return deg * CGFloat.pi / 180.0
}
| mit |
khoren93/SwiftHub | SwiftHub/Common/TableViewController.swift | 1 | 3461 | //
// TableViewController.swift
// SwiftHub
//
// Created by Khoren Markosyan on 1/4/17.
// Copyright © 2017 Khoren Markosyan. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import KafkaRefresh
class TableViewController: ViewController, UIScrollViewDelegate {
let headerRefreshTrigger = PublishSubject<Void>()
let footerRefreshTrigger = PublishSubject<Void>()
let isHeaderLoading = BehaviorRelay(value: false)
let isFooterLoading = BehaviorRelay(value: false)
lazy var tableView: TableView = {
let view = TableView(frame: CGRect(), style: .plain)
view.emptyDataSetSource = self
view.emptyDataSetDelegate = self
view.rx.setDelegate(self).disposed(by: rx.disposeBag)
return view
}()
var clearsSelectionOnViewWillAppear = true
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if clearsSelectionOnViewWillAppear == true {
deselectSelectedRow()
}
}
override func makeUI() {
super.makeUI()
stackView.spacing = 0
stackView.insertArrangedSubview(tableView, at: 0)
tableView.bindGlobalStyle(forHeadRefreshHandler: { [weak self] in
self?.headerRefreshTrigger.onNext(())
})
tableView.bindGlobalStyle(forFootRefreshHandler: { [weak self] in
self?.footerRefreshTrigger.onNext(())
})
isHeaderLoading.bind(to: tableView.headRefreshControl.rx.isAnimating).disposed(by: rx.disposeBag)
isFooterLoading.bind(to: tableView.footRefreshControl.rx.isAnimating).disposed(by: rx.disposeBag)
tableView.footRefreshControl.autoRefreshOnFoot = true
error.subscribe(onNext: { [weak self] (error) in
self?.tableView.makeToast(error.description, title: error.title, image: R.image.icon_toast_warning())
}).disposed(by: rx.disposeBag)
}
override func updateUI() {
super.updateUI()
}
override func bindViewModel() {
super.bindViewModel()
viewModel?.headerLoading.asObservable().bind(to: isHeaderLoading).disposed(by: rx.disposeBag)
viewModel?.footerLoading.asObservable().bind(to: isFooterLoading).disposed(by: rx.disposeBag)
let updateEmptyDataSet = Observable.of(isLoading.mapToVoid().asObservable(), emptyDataSetImageTintColor.mapToVoid(), languageChanged.asObservable()).merge()
updateEmptyDataSet.subscribe(onNext: { [weak self] () in
self?.tableView.reloadEmptyDataSet()
}).disposed(by: rx.disposeBag)
}
}
extension TableViewController {
func deselectSelectedRow() {
if let selectedIndexPaths = tableView.indexPathsForSelectedRows {
selectedIndexPaths.forEach({ (indexPath) in
tableView.deselectRow(at: indexPath, animated: false)
})
}
}
}
extension TableViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let view = view as? UITableViewHeaderFooterView, let textLabel = view.textLabel {
textLabel.font = UIFont.systemFont(ofSize: 15)
textLabel.theme.textColor = themeService.attribute { $0.text }
view.contentView.theme.backgroundColor = themeService.attribute { $0.primaryDark }
}
}
}
| mit |
Wondgirl/WTZB | WTZB/WTZB/AppDelegate.swift | 1 | 2169 | //
// AppDelegate.swift
// WTZB
//
// Created by Wondergirl on 2016/12/5.
// Copyright © 2016年 Wondgirl. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
Brightify/DataMapper | Source/Core/Transformation/Transformations/Date/CustomDateFormatTransformation.swift | 1 | 662 | //
// CustomDateFormatTransformation.swift
// DataMapper
//
// Created by Tadeas Kriz on 16/07/15.
// Copyright © 2016 Brightify. All rights reserved.
//
import Foundation
public struct CustomDateFormatTransformation: DelegatedTransformation {
public typealias Object = Date
public let transformationDelegate: AnyTransformation<Date>
public init(formatString: String) {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = formatString
transformationDelegate = DateFormatterTransformation(dateFormatter: formatter).typeErased()
}
}
| mit |
kaltura/developer-platform | test/golden/implicit_object_type/swift.swift | 1 | 612 | var searchParams = ESearchEntryParams()
searchParams.searchOperator = ESearchEntryOperator()
searchParams.searchOperator.operator = ESearchOperatorType.AND_OP
searchParams.searchOperator.searchItems = []
searchParams.searchOperator.searchItems[0] = ESearchCaptionItem()
searchParams.searchOperator.searchItems[0].searchTerm = "asdf"
var pager = Pager()
let requestBuilder = ESearchService.searchEntry(searchParams: searchParams, pager: pager)
requestBuilder.set(completion: {(result: ESearchEntryResponse?, error: ApiException?) in
print(result!)
done()
})
executor.send(request: requestBuilder.build(client)) | agpl-3.0 |
ckhsponge/iairportsdb | iAirportsDB/Classes/IADBNavigationAid.swift | 1 | 2967 | //
// IADBNavigationAid.swift
// iAirportsDB
//
// Created by Christopher Hobbs on 8/21/16.
// Copyright © 2016 Toonsy Net. All rights reserved.
//
import Foundation
import CoreData
import CoreLocation
@objc(IADBNavigationAid)
open class IADBNavigationAid: IADBLocation {
@NSManaged open var dmeKhz: Int32
@NSManaged open var elevationFeet: NSNumber?
@NSManaged open var khz: Int32
@NSManaged open var name: String
@NSManaged open var type: String
open lazy var mhz:Double = {
return Double(self.khz) / 1000.0
}()
override open func setCsvValues( _ values: [String: String] ) {
//"id","filename","ident","name","type","frequency_khz","latitude_deg","longitude_deg","elevation_ft","iso_country","dme_frequency_khz","dme_channel","dme_latitude_deg","dme_longitude_deg","dme_elevation_ft","slaved_variation_deg","magnetic_variation_deg","usageType","power","associated_airport",
//print(values)
self.dmeKhz = Int32(values["dme_frequency_khz"]!) ?? -1
self.elevationFeet = IADBModel.parseIntNumber(text:values["elevation_ft"])
self.identifier = values["ident"] ?? ""
self.khz = Int32(values["frequency_khz"]!) ?? -1
self.latitude = Double(values["latitude_deg"]!)!
self.longitude = Double(values["longitude_deg"]!)!
self.name = values["name"] ?? ""
self.type = values["type"] ?? ""
}
//begin convenience functions for type casting
open override class func findNear(_ location: CLLocation, withinNM distance: CLLocationDistance) -> IADBCenteredArrayNavigationAids {
return IADBCenteredArrayNavigationAids(centeredArray: super.findNear(location, withinNM: distance))
}
open override class func find(identifier: String) -> IADBNavigationAid? {
let model = super.find(identifier:identifier)
guard let typed = model as? IADBNavigationAid else {
print("Invalid type found \(String(describing: model))")
return nil
}
return typed
}
open override class func findAll(identifier: String) -> IADBCenteredArrayNavigationAids {
return IADBCenteredArrayNavigationAids(centeredArray: super.findAll(identifier:identifier))
}
open override class func findAll(identifier: String, types: [String]?) -> IADBCenteredArrayNavigationAids {
return IADBCenteredArrayNavigationAids(centeredArray: super.findAll(identifier:identifier, types: types))
}
open override class func findAll(identifiers: [String], types: [String]?) -> IADBCenteredArrayNavigationAids {
return IADBCenteredArrayNavigationAids(centeredArray: super.findAll(identifiers:identifiers, types: types))
}
open override class func findAll(predicate: NSPredicate) -> IADBCenteredArrayNavigationAids {
return IADBCenteredArrayNavigationAids(centeredArray: super.findAll(predicate:predicate))
}
//end convenience functions
}
| mit |
tzef/BmoImageLoader | BmoImageLoader/Classes/BmoPathExtension.swift | 1 | 767 | //
// BmoPathExtention.swift
// CrazyMikeSwift
//
// Created by LEE ZHE YU on 2016/8/6.
// Copyright © 2016年 B1-Media. All rights reserved.
//
import UIKit
extension CGPath {
func insetPath(_ percent: CGFloat) -> CGPath {
let path = UIBezierPath(cgPath: self)
let translatePoint = CGPoint(x: path.bounds.width * percent / 2 + path.bounds.origin.x * percent,
y: path.bounds.height * percent / 2 + path.bounds.origin.y * percent)
var transform = CGAffineTransform.identity
transform = transform.translatedBy(x: translatePoint.x, y: translatePoint.y)
transform = transform.scaledBy(x: 1 - percent, y: 1 - percent)
path.apply(transform)
return path.cgPath
}
}
| mit |
yoman07/SwiftBackgroundLocation | SwiftBackgroundLocation/Classes/Result.swift | 1 | 87 | import Foundation
public enum Result<T> {
case Success(T)
case Error(Error)
}
| mit |
Archerlly/ACRouter | ACRouter/Classes/ACRouter.swift | 1 | 5356 | //
// ACRouter.swift
// ACRouter
//
// Created by SnowCheng on 11/03/2017.
// Copyright © 2017 Archerlly. All rights reserved.
//
import Foundation
public class ACRouter: ACRouterParser {
// MARK: - Constants
public typealias FailedHandleBlock = ([String: AnyObject]) -> Void
public typealias RelocationHandleBlock = (String) -> String?
public typealias RouteResponse = (pattern: ACRouterPattern?, queries: [String: AnyObject])
public typealias MatchResult = (matched: Bool, queries: [String: AnyObject])
// MARK: - Private property
private var patterns = [ACRouterPattern]()
private var interceptors = [ACRouterInterceptor]()
private var relocationHandle: RelocationHandleBlock?
private var matchFailedHandle: FailedHandleBlock?
// MARK: - Public property
static let shareInstance = ACRouter()
// MARK: - Public method
func addRouter(_ patternString: String,
priority: uint = 0,
handle: @escaping ACRouterPattern.HandleBlock) {
let pattern = ACRouterPattern.init(patternString, priority: priority, handle: handle)
patterns.append(pattern)
patterns.sort { $0.priority > $1.priority }
}
func addInterceptor(_ whiteList: [String] = [String](),
priority: uint = 0,
handle: @escaping ACRouterInterceptor.InterceptorHandleBlock) {
let interceptor = ACRouterInterceptor.init(whiteList, priority: priority, handle: handle)
interceptors.append(interceptor)
interceptors.sort { $0.priority > $1.priority }
}
func addGlobalMatchFailedHandel(_ handel: @escaping FailedHandleBlock) {
matchFailedHandle = handel
}
func addRelocationHandle(_ handel: @escaping RelocationHandleBlock) {
relocationHandle = handel
}
func removeRouter(_ patternString: String) {
patterns = patterns.filter{ $0.patternString != patternString }
}
func canOpenURL(_ urlString: String) -> Bool {
return ac_matchURL(urlString).pattern != nil
}
func requestURL(_ urlString: String, userInfo: [String: AnyObject] = [String: AnyObject]()) -> RouteResponse {
return ac_matchURL(urlString, userInfo: userInfo)
}
// MARK: - Private method
private func ac_matchURL(_ urlString: String, userInfo: [String: AnyObject] = [String: AnyObject]()) -> RouteResponse {
let request = ACRouterRequest.init(urlString)
var queries = request.queries
var matched: ACRouterPattern?
if let patternString = relocationHandle?(urlString),
let firstMatched = patterns.filter({ $0.patternString == patternString }).first {
//relocation
matched = firstMatched
} else {
//filter the scheme and the count of paths not matched
let matchedPatterns = patterns.filter{ $0.sheme == request.sheme && $0.patternPaths.count == request.paths.count }
for pattern in matchedPatterns {
let result = ac_matchPattern(request, pattern: pattern)
if result.matched {
matched = pattern
queries.ac_combine(result.queries)
break
}
}
}
guard let currentPattern = matched else {
//not matched
var info = [ACRouter.matchFailedKey : urlString as AnyObject]
info.ac_combine(userInfo)
matchFailedHandle?(info)
print("not matched: \(urlString)")
return (nil, [String: AnyObject]())
}
guard ac_intercept(currentPattern.patternString, queries: queries) else {
print("interceped: \(urlString)")
return (nil, [String: AnyObject]())
}
queries.ac_combine([ACRouter.requestURLKey : urlString as AnyObject])
queries.ac_combine(userInfo)
return (currentPattern, queries)
}
private func ac_matchPattern(_ request: ACRouterRequest, pattern: ACRouterPattern) -> MatchResult {
var requestPaths = request.paths
var pathQuery = [String: AnyObject]()
//replace params
pattern.paramsMatchDict.forEach({ (name, index) in
let requestPathQueryValue = requestPaths[index] as AnyObject
pathQuery[name] = requestPathQueryValue
requestPaths[index] = ACRouterPattern.PatternPlaceHolder
})
let matchString = requestPaths.joined(separator: "/")
if matchString == pattern.matchString {
return (true, pathQuery)
} else {
return (false, [String: AnyObject]())
}
}
//Intercep the request and return whether should continue
private func ac_intercept(_ matchedPatternString: String, queries: [String: AnyObject]) -> Bool {
for interceptor in self.interceptors where !interceptor.whiteList.contains(matchedPatternString) {
if !interceptor.handle(queries) {
//interceptor handle return true will continue interceptor
return false
}
}
return true
}
}
| mit |
mitsuse/mastodon-swift | Sources/Json_Visibility.swift | 1 | 168 | import Himotoki
public enum VisibilityJson: String {
case `public`
case unlisted
case `private`
case direct
}
extension VisibilityJson: Decodable {
}
| mit |
xtcan/playerStudy_swift | TCVideo_Study/TCVideo_Study/Classes/Live/View/GiftListView.swift | 1 | 580 | //
// GiftListView.swift
// TCVideo_Study
//
// Created by tcan on 17/6/22.
// Copyright © 2017年 tcan. All rights reserved.
//
import UIKit
class GiftListView: UIView {
// MARK: 控件属性
@IBOutlet weak var giftView: UIView!
@IBOutlet weak var sendGiftBtn: UIButton!
}
extension GiftListView {
@IBAction func sendGiftBtnClick() {
// let package = giftVM.giftlistData[currentIndexPath!.section]
// let giftModel = package.list[currentIndexPath!.item]
// delegate?.giftListView(giftView: self, giftModel: giftModel)
}
}
| apache-2.0 |
ustwo/formvalidator-swift | Sources/Conditions/AlphanumericCondition.swift | 1 | 1568 | //
// AlphanumericCondition.swift
// FormValidatorSwift
//
// Created by Aaron McTavish on 13/01/2016.
// Copyright © 2016 ustwo Fampany Ltd. All rights reserved.
//
import Foundation
/**
* The `AlphanumericCondition` checks a string for occurrences of letters and/or numbers.
*/
public struct AlphanumericCondition: ConfigurableCondition {
// MARK: - Properties
public var localizedViolationString = StringLocalization.sharedInstance.localizedString("US2KeyConditionViolationAlphanumeric", comment: "")
public let regex: String
public var shouldAllowViolation = true
public let configuration: AlphanumericConfiguration
// MARK: - Initializers
public init(configuration: AlphanumericConfiguration) {
self.configuration = configuration
let regexLettersNumbers = configuration.allowsUnicode ? "\\p{L}\\p{N}" : "a-zA-Z0-9"
let regexWhiteSpace = configuration.allowsWhitespace ? "\\s" : ""
regex = "[\(regexLettersNumbers)\(regexWhiteSpace)]"
}
// MARK: - Check
public func check(_ text: String?) -> Bool {
guard let sourceText = text,
!sourceText.isEmpty,
let regExpression = try? NSRegularExpression(pattern: regex, options: .caseInsensitive) else {
return false
}
return regExpression.numberOfMatches(in: sourceText, options: [], range: NSRange(location: 0, length: sourceText.count)) == sourceText.count
}
}
| mit |
emilybache/GildedRose-Refactoring-Kata | swift/Package.swift | 1 | 548 | // swift-tools-version:5.5
import PackageDescription
let package = Package(
name: "GildedRose",
products: [
.library(
name: "GildedRose",
targets: ["GildedRose"]
),
],
targets: [
.target(
name: "GildedRose",
dependencies: []
),
.target(
name: "GildedRoseApp",
dependencies: ["GildedRose"]
),
.testTarget(
name: "GildedRoseTests",
dependencies: ["GildedRose"]
),
]
)
| mit |
yvzzztrk/SwiftTemplateProject | Project/template/Settings/ConstantsUAT.swift | 1 | 420 | //
// ConstantsUAT.swift
// template
//
// Created by YAVUZ ÖZTÜRK on 10/02/2017.
// Copyright © 2017 Templete Project INC. All rights reserved.
//
import Foundation
let connectionDebug = false
let defaultEndpointType = EndpointType.uat
extension AppDelegate {
func initializeGlobals() {
initializeNSURLSessionConfiguration()
initializeEndpointType()
initializeAppearance()
}
}
| apache-2.0 |
superbderrick/SummerSlider | useCases/vastExample/vastExample/ViewController.swift | 1 | 749 | //
// ViewController.swift
// vastExample
//
// Created by Kang Jinyeoung on 10/09/2017.
// Copyright © 2017 SuperbDerrick. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playVideo(_ sender: Any) {
let signUpVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "playerController")
self.navigationController?.pushViewController(signUpVC, animated: true)
}
}
| mit |
karstengresch/layout_studies | countidon/countidon/ShapeButton.swift | 1 | 2405 | //
// ShapeButton.swift
// countidon
//
// Created by Karsten Gresch on 15.10.15.
// Copyright © 2015 Closure One. All rights reserved.
//
import UIKit
@IBDesignable
class ShapeButton: UIControl {
// source: http://stackoverflow.com/questions/27432736/how-to-create-an-ibinspectable-of-type-enum?rq=1
enum CornerType: String {
case Rounded = "rounded"
case Circle = "circle"
}
var cornerType = CornerType.Rounded
var labelText = "ShapeButton"
var segueIdentifier = ""
@available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'cornerType' instead.")
@IBInspectable var cornerTypeName: String? {
willSet {
if let newCornerType = CornerType(rawValue: newValue?.lowercased() ?? "") {
cornerType = newCornerType
}
}
}
@IBInspectable var radiusWidth: CGFloat = 30
@IBInspectable var radiusHeight: CGFloat = 30
@IBInspectable let shapeButtonLabel: UILabel = UILabel(frame: CGRect(x: 20.0, y: 30.0, width: 300.0, height: 30.0))
override func layoutSubviews() {
let shapeLayer = CAShapeLayer()
switch cornerType {
case .Rounded:
shapeLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: [UIRectCorner.topLeft, UIRectCorner.topRight, UIRectCorner.bottomLeft, UIRectCorner.bottomRight], cornerRadii: CGSize(width: 30, height: 30)).cgPath
case .Circle:
shapeLayer.path = UIBezierPath(ovalIn: self.bounds).cgPath
}
layer.mask = shapeLayer
setupLabels()
}
func setupLabels() {
shapeButtonLabel.numberOfLines = 1;
shapeButtonLabel.baselineAdjustment = UIBaselineAdjustment.alignBaselines
shapeButtonLabel.adjustsFontSizeToFitWidth = true
shapeButtonLabel.frame = self.bounds
shapeButtonLabel.backgroundColor = UIColor.clear
shapeButtonLabel.text = self.labelText
shapeButtonLabel.textColor = UIColor.white
shapeButtonLabel.font = UIFont.systemFont(ofSize: 28.0)
shapeButtonLabel.textAlignment = .center
shapeButtonLabel.drawText(in: self.bounds)
self.addSubview(shapeButtonLabel)
self.setNeedsDisplay()
}
}
import UIKit.UIGestureRecognizerSubclass
private class TapRecognizer: UITapGestureRecognizer {
func handleTap(sender: UITapGestureRecognizer) {
print("Tapped!")
if sender.state == .ended {
// handling code
print("Tap ended!")
}
}
}
| unlicense |
kstaring/swift | validation-test/compiler_crashers_fixed/00931-swift-typebase-getcanonicaltype.swift | 11 | 434 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
protocol A : Boolean, A {
typealias e : e
| apache-2.0 |
natecook1000/swift | test/SourceKit/CompileNotifications/diagnostics.swift | 1 | 4943 | // REQUIRES: rdar39260564
// RUN: %sourcekitd-test -req=track-compiles == -req=sema %s -- %s | %FileCheck %s -check-prefix=NODIAGS
// NODIAGS: key.notification: source.notification.compile-did-finish
// NODIAGS-NEXT: key.diagnostics: [
// NODIAGS-NEXT: ]
// RUN: %sourcekitd-test -req=track-compiles == -req=sema %S/Inputs/parse-error.swift -- %S/Inputs/parse-error.swift | %FileCheck %s -check-prefix=PARSE
// PARSE: key.notification: source.notification.compile-did-finish
// PARSE-NEXT: key.diagnostics: [
// PARSE-NEXT: {
// PARSE-NEXT: key.line: 1
// PARSE-NEXT: key.column: 6
// PARSE-NEXT: key.filepath: "{{.*}}parse-error.swift"
// PARSE-NEXT: key.severity: source.diagnostic.severity.error
// PARSE-NEXT: key.description: "function name
// PARSE-NEXT: }
// PARSE-NEXT: ]
// RUN: %sourcekitd-test -req=track-compiles == -req=sema %S/Inputs/parse-error-with-sourceLocation.swift -- %S/Inputs/parse-error-with-sourceLocation.swift | %FileCheck %s -check-prefix=PARSE-WITH-SOURCELOCATION
// PARSE-WITH-SOURCELOCATION: key.notification: source.notification.compile-did-finish
// PARSE-WITH-SOURCELOCATION-NEXT: key.diagnostics: [
// PARSE-WITH-SOURCELOCATION-NEXT: {
// PARSE-WITH-SOURCELOCATION-NEXT: key.line: 2000
// PARSE-WITH-SOURCELOCATION-NEXT: key.column: 6
// PARSE-WITH-SOURCELOCATION-NEXT: key.filepath: "custom.swuft"
// PARSE-WITH-SOURCELOCATION-NEXT: key.severity: source.diagnostic.severity.error
// PARSE-WITH-SOURCELOCATION-NEXT: key.description: "function name
// PARSE-WITH-SOURCELOCATION-NEXT: }
// PARSE-WITH-SOURCELOCATION-NEXT: ]
// Diagnostic from other file.
// RUN: %sourcekitd-test -req=track-compiles == -req=sema %s -- %s %S/Inputs/parse-error.swift | %FileCheck %s -check-prefix=PARSE
// RUN: %sourcekitd-test -req=track-compiles == -req=sema %S/Inputs/sema-error.swift -- %S/Inputs/sema-error.swift | %FileCheck %s -check-prefix=SEMA
// SEMA: key.notification: source.notification.compile-did-finish
// SEMA-NEXT: key.diagnostics: [
// SEMA-NEXT: {
// SEMA-NEXT: key.line: 1
// SEMA-NEXT: key.column: 5
// SEMA-NEXT: key.filepath: "{{.*}}sema-error.swift"
// SEMA-NEXT: key.severity: source.diagnostic.severity.error
// SEMA-NEXT: key.description: "use of
// SEMA-NEXT: key.ranges: [
// RUN: %sourcekitd-test -req=track-compiles == -req=sema %s -- %s -Xcc -include -Xcc /doesnotexist | %FileCheck %s -check-prefix=CLANG_IMPORTER
// CLANG_IMPORTER: key.notification: source.notification.compile-did-finish,
// CLANG_IMPORTER-NEXT: key.diagnostics: [
// CLANG_IMPORTER-NEXT: {
// CLANG_IMPORTER-NEXT: key.line:
// CLANG_IMPORTER-NEXT: key.column:
// CLANG_IMPORTER-NEXT: key.filepath: "<{{.*}}>"
// CLANG_IMPORTER-NEXT: key.severity: source.diagnostic.severity.error,
// CLANG_IMPORTER-NEXT: key.description: {{.*}}not found
// RUN: %sourcekitd-test -req=track-compiles == -req=sema %s -- %s -Xcc -ivfsoverlay -Xcc /doesnotexist | %FileCheck %s -check-prefix=CLANG_IMPORTER_UNKNOWN
// CLANG_IMPORTER_UNKNOWN: key.notification: source.notification.compile-did-finish,
// CLANG_IMPORTER_UNKNOWN-NEXT: key.diagnostics: [
// CLANG_IMPORTER_UNKNOWN-NEXT: {
// CLANG_IMPORTER_UNKNOWN-NEXT: key.filepath: "<unknown>"
// CLANG_IMPORTER_UNKNOWN-NEXT: key.severity: source.diagnostic.severity.error,
// CLANG_IMPORTER_UNKNOWN-NEXT: key.offset: 0
// CLANG_IMPORTER_UNKNOWN-NEXT: key.description: "virtual filesystem{{.*}}not found
// Note: we're missing the "compiler is in code completion mode" diagnostic,
// which is probably just as well.
// RUN: %sourcekitd-test -req=track-compiles == -req=complete -offset=0 %s -- %s | %FileCheck %s -check-prefix=NODIAGS
// RUN: %sourcekitd-test -req=track-compiles == -req=complete -pos=2:1 %S/Inputs/sema-error.swift -- %S/Inputs/sema-error.swift | %FileCheck %s -check-prefix=SEMA
// FIXME: invalid arguments cause us to early-exit and not send the notifications
// RUN_DISABLED: %sourcekitd-test -req=track-compiles == -req=sema %s -- %s -invalid-arg | %FileCheck %s -check-prefix=INVALID_ARG
// RUN: %sourcekitd-test -req=track-compiles == -req=sema %s -- %s -Xcc -invalid-arg | %FileCheck %s -check-prefix=INVALID_ARG_CLANG
// INVALID_ARG_CLANG: key.notification: source.notification.compile-did-finish,
// INVALID_ARG_CLANG-NEXT: key.diagnostics: [
// INVALID_ARG_CLANG-NEXT: {
// INVALID_ARG_CLANG-NEXT: key.filepath: "<unknown>"
// INVALID_ARG_CLANG-NEXT: key.severity: source.diagnostic.severity.warning,
// INVALID_ARG_CLANG-NEXT: key.offset: 0
// INVALID_ARG_CLANG-NEXT: key.description: "argument unused
// Ignore the spurious -wmo + -enable-batch-mode warning.
// RUN: %sourcekitd-test -req=track-compiles == -req=sema %s -- %s -enable-batch-mode | %FileCheck %s -check-prefix=NODIAGS
// RUN: %sourcekitd-test -req=track-compiles == -req=complete -offset=0 %s -- %s -enable-batch-mode | %FileCheck %s -check-prefix=NODIAGS
| apache-2.0 |
mleiv/MEGameTracker | MEGameTracker/Views/Common/Spinnerable/SpinnerNib.swift | 1 | 1831 | //
// SpinnerNib.swift
// MEGameTracker
//
// Created by Emily Ivie on 5/14/2016.
// Copyright © 2016 urdnot. All rights reserved.
//
import UIKit
final public class SpinnerNib: UIView {
@IBOutlet weak var spinner: UIActivityIndicatorView?
@IBOutlet weak var spinnerLabel: MarkupLabel?
@IBOutlet weak var spacerView: UIView?
@IBOutlet public weak var progressView: UIProgressView?
var title: String? {
didSet {
if oldValue != title {
setupTitle()
}
}
}
var isShowProgress: Bool = false {
didSet {
if oldValue != isShowProgress {
setupProgress()
}
}
}
public func setup() {
setupTitle()
setupProgress()
}
public func setupTitle() {
spinnerLabel?.text = title
spinnerLabel?.isHidden = !(title?.isEmpty == false)
layoutIfNeeded()
}
public func setupProgress() {
spacerView?.isHidden = !isShowProgress
progressView?.isHidden = !isShowProgress
layoutIfNeeded()
}
public func start() {
setupProgress()
progressView?.progress = 0.0
spinner?.startAnimating()
isHidden = false
}
public func startSpinning() {
spinner?.startAnimating()
progressView?.progress = 0.0
}
public func stop() {
spinner?.stopAnimating()
isHidden = true
}
public func updateProgress(percentCompleted: Int) {
let decimalCompleted = Float(percentCompleted) / 100.0
progressView?.setProgress(decimalCompleted, animated: true)
}
public func changeMessage(_ title: String) {
spinnerLabel?.text = title
}
public class func loadNib(title: String? = nil) -> SpinnerNib? {
let bundle = Bundle(for: SpinnerNib.self)
if let view = bundle.loadNibNamed("SpinnerNib", owner: self, options: nil)?.first as? SpinnerNib {
// view.spinner?.color = Styles.colors.tint // Styles.colors.tint
view.title = title
return view
}
return nil
}
}
| mit |
vickyisrulin/AM_App | AM_App/AM_App/ThakorjiDetail.swift | 1 | 2299 | //
// ThakorjiDetail.swift
// AM_App
//
// Created by Vicky Rana on 3/5/17.
// Copyright © 2017 Vicky Rana. All rights reserved.
//
import Foundation
import UIKit
class ThakorjiImage: UIViewController {
var mandir = String()
var date = String()
var id = Int16()
var count = Int16()
var templeurl = String()
// var imagesURLS = [String]()
@IBOutlet weak var ThakorjiImage: UIScrollView!
@IBOutlet weak var mandirLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
override func viewDidLoad() {
if let templeint:Int16 = (id) as? Int16
{
// var templeurl = ""
if templeint == 1
{ templeurl = "india" }
else if templeint == 2
{ templeurl = "uk" }
else if templeint == 3
{ templeurl = "usa" }
else if templeint == 4
{ templeurl = "kharghar" }
else if templeint == 5
{ templeurl = "surat" }
else if templeint == 6
{ templeurl = "vemar" }
else if templeint == 7
{ templeurl = "amdavad" }
}
mandirLabel.text = mandir
dateLabel.text = date
ThakorjiImage.frame = view.frame
//for i in 0..<count {
// imagesURLS.append("http://anoopam.org/thakorjitoday/\(id)/images/god0\(i+1)L.jpg") }
for j in 0..<count {
let imageview = UIImageView()
imageview.sd_setImage(with: URL(string: "http://anoopam.org/thakorjitoday/\(templeurl)/images/god0\(j+1)L.jpg"))//,placeholderImage: UIImage(named: "Placeholder.png"))
imageview.contentMode = .scaleAspectFit
let xPos = self.view.frame.width * CGFloat(j)
imageview.frame = CGRect(x: xPos, y: 0, width: self.view.frame.width, height: self.view.frame.height)
ThakorjiImage.contentSize.width = ThakorjiImage.frame.width * CGFloat(j+1)
ThakorjiImage.addSubview(imageview)
}
}
}
| mit |
DungntVccorp/Game | P/Sources/P/ConcurrentOperation.swift | 1 | 2623 | //
// BaseOperation.swift
// P
//
// Created by Nguyen Dung on 4/27/17.
//
//
import Foundation
protocol ConcurrentOperationDelegate {
func finishOperation(_ type : Int,_ replyMsg : GSProtocolMessage?,_ client : TcpClient)
}
open class ConcurrentOperation : Operation{
enum State {
case ready
case executing
case finished
func asKeyPath() -> String {
switch self {
case .ready:
return "isReady"
case .executing:
return "isExecuting"
case .finished:
return "isFinished"
}
}
}
var state: State {
willSet {
willChangeValue(forKey: newValue.asKeyPath())
willChangeValue(forKey: state.asKeyPath())
}
didSet {
didChangeValue(forKey: oldValue.asKeyPath())
didChangeValue(forKey: state.asKeyPath())
}
}
private var delegate : ConcurrentOperationDelegate!
var clientExcute : TcpClient!
var excuteMessage : GSProtocolMessage!
override init() {
state = .ready
super.init()
}
convenience init(_ delegate : ConcurrentOperationDelegate?,_ client : TcpClient,_ msg : GSProtocolMessage) {
self.init()
if(delegate != nil){
self.delegate = delegate!
}
self.clientExcute = client
self.excuteMessage = msg
}
// MARK: - NSOperation
override open var isReady: Bool {
return state == .ready
}
override open var isExecuting: Bool {
return state == .executing
}
override open var isFinished: Bool {
return state == .finished
}
override open var isAsynchronous: Bool {
return true
}
override open func start() {
if self.isCancelled {
state = .finished
}else{
state = .ready
main()
}
}
open func TcpExcute() -> (Int,replyMsg : GSProtocolMessage?){
return (0,nil)
}
override open func main() {
if self.isCancelled {
state = .finished
}else{
state = .executing
debugPrint("Run OP \(excuteMessage.headCodeId) : \(excuteMessage.subCodeId)")
let ex = self.TcpExcute()
if(self.delegate != nil){
self.delegate.finishOperation(ex.0,ex.1,self.clientExcute)
}
state = .finished
}
}
deinit {
debugPrint("Finish Operation")
}
}
| mit |
dduan/swift | test/DebugInfo/line-directive.swift | 1 | 699 | func markUsed<T>(t: T) {}
func f() {
if 1==1 {
#sourceLocation(file: "abc.swift", line: 42)
markUsed("Hello World")
#sourceLocation()
}
markUsed("Test")
#sourceLocation(file: "abc.swift", line: 142)
markUsed("abc again")
#sourceLocation(file: "def.swift", line: 142)
markUsed("jump directly to def")
}
// RUN: %target-swift-frontend -primary-file %s -S -g -o - | FileCheck %s
// CHECK: .file [[MAIN:.*]] "{{.*}}line-directive.swift"
// CHECK: .loc [[MAIN]] 1
// CHECK: .file [[ABC:.*]] "abc.swift"
// CHECK: .loc [[ABC]] 42
// CHECK: .loc [[MAIN]] 8
// CHECK: .loc [[ABC]] 142
// CHECK: .file [[DEF:.*]] "def.swift"
// CHECK: .loc [[DEF]] 142
// CHECK: .asciz "{{.*}}test/DebugInfo"
| apache-2.0 |
nuclearace/SwiftDiscord | Sources/SwiftDiscord/DiscordLogger.swift | 1 | 3197 | // The MIT License (MIT)
// Copyright (c) 2016 Erik Little
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without
// limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
import Foundation
/// Represents the level of verbosity for the logger.
public enum DiscordLogLevel {
/// Log nothing.
case none
/// Log connecting, disconnecting, events (but not content), etc.
case info
/// Log content of events.
case verbose
/// Log everything.
case debug
}
/// Declares that a type will act as a logger.
public protocol DiscordLogger {
// MARK: Properties
/// Whether to log or not.
var level: DiscordLogLevel { get set }
// MARK: Methods
/// Normal log messages.
func log( _ message: @autoclosure () -> String, type: String)
/// More info on log messages.
func verbose(_ message: @autoclosure () -> String, type: String)
/// Debug messages.
func debug(_ message: @autoclosure () -> String, type: String)
/// Error Messages.
func error(_ message: @autoclosure () -> String, type: String)
}
public extension DiscordLogger {
/// Normal log messages.
func log(_ message: @autoclosure () -> String, type: String) {
guard level == .info || level == .verbose || level == .debug else { return }
abstractLog("LOG", message: message(), type: type)
}
/// More info on log messages.
func verbose(_ message: @autoclosure () -> String, type: String) {
guard level == .verbose || level == .debug else { return }
abstractLog("VERBOSE", message: message(), type: type)
}
/// Debug messages.
func debug(_ message: @autoclosure () -> String, type: String) {
guard level == .debug else { return }
abstractLog("DEBUG", message: message(), type: type)
}
/// Error Messages.
func error(_ message: @autoclosure () -> String, type: String) {
abstractLog("ERROR", message: message(), type: type)
}
private func abstractLog(_ logType: String, message: String, type: String) {
NSLog("\(logType): \(type): \(message)")
}
}
class DefaultDiscordLogger : DiscordLogger {
static var Logger: DiscordLogger = DefaultDiscordLogger()
var level = DiscordLogLevel.none
}
| mit |
kkireto/SwiftUtils | LabelUtils.swift | 1 | 3220 | //The MIT License (MIT)
//
//Copyright (c) 2014 Kireto
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of
//this software and associated documentation files (the "Software"), to deal in
//the Software without restriction, including without limitation the rights to
//use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//the Software, and to permit persons to whom the Software is furnished to do so,
//subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
class LabelUtils: NSObject {
class func label(frame: CGRect, font: UIFont, color: UIColor, alignment: NSTextAlignment, text: NSString) -> UILabel {
var retValue = UILabel (frame: frame)
retValue.backgroundColor = UIColor.clearColor()
retValue.font = font
retValue.textColor = color
retValue.textAlignment = alignment
retValue.text = text
return retValue
}
class func label(frame: CGRect, numberOfLines: Int, font: UIFont, color: UIColor, alignment: NSTextAlignment, text: NSString) -> UILabel {
var retValue = UILabel (frame: frame)
retValue.backgroundColor = UIColor.clearColor()
retValue.numberOfLines = numberOfLines
retValue.font = font
retValue.textColor = color
retValue.textAlignment = alignment
retValue.text = text
return retValue
}
class func label(frame: CGRect, font: UIFont, color: UIColor, alignment: NSTextAlignment, text: NSString, shadowColor: UIColor, shadowOffset: CGSize) -> UILabel {
var retValue = LabelUtils.label(frame, font: font, color: color, alignment: alignment, text: text)
retValue.shadowColor = shadowColor
retValue.shadowOffset = shadowOffset
return retValue
}
class func textSize (text: NSString, font: UIFont) -> CGSize {
var attributes = NSDictionary(object: font, forKey: NSFontAttributeName)
return text.sizeWithAttributes(attributes)
}
class func textSize (text: NSString, font: UIFont, lineBreakMode: NSLineBreakMode, initialSize: CGSize) -> CGSize {
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = lineBreakMode
var attributes = NSDictionary(objectsAndKeys:
font, NSFontAttributeName,
paragraphStyle.copy(), NSParagraphStyleAttributeName)
var textRect = text.boundingRectWithSize(initialSize,
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: attributes,
context: nil)
return textRect.size
}
}
| mit |
nickplee/Aestheticam | Aestheticam/Vendor/RandomKit/Tests/RandomKitTests/ConstantTests.swift | 2 | 2397 | //
// ConstantTests.swift
// RandomKitTests
//
// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Nikolai Vazquez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
import Foundation
import RandomKit
struct ConstantRandomGenerator: RandomBytesGenerator {
var value: UInt64
mutating func randomBytes() -> UInt64 {
return value
}
}
class ConstantTests: XCTestCase {
static let allTests = [("testRandomHalfOpenEdgeCase", testRandomHalfOpenEdgeCase),
("testRandomClosedEdgeCase", testRandomClosedEdgeCase),
("testRandomOpenEdgeCase", testRandomOpenEdgeCase)]
static let generatorToTest = Xoroshiro.self
let testCount: UInt = 100_000
func testRandomHalfOpenEdgeCase() {
var gen = ConstantRandomGenerator(value: .max)
XCTAssertNotEqual(gen.randomHalfOpen32(), 1.0)
XCTAssertNotEqual(gen.randomHalfOpen64(), 1.0)
}
func testRandomClosedEdgeCase() {
var gen = ConstantRandomGenerator(value: .max)
XCTAssertEqual(gen.randomClosed32(), 1.0)
XCTAssertEqual(gen.randomClosed64(), 1.0)
}
func testRandomOpenEdgeCase() {
var gen = ConstantRandomGenerator(value: 0)
XCTAssertNotEqual(gen.randomOpen32(), 0.0)
XCTAssertNotEqual(gen.randomOpen64(), 0.0)
}
}
| mit |
DigitalShooting/DSM-iOS | DSM-iOS/SingleLineViewController.swift | 1 | 9596 | //
// FirstViewController.swift
// DSM-iOS
//
// Created by Jannik Lorenz on 31.10.15.
// Copyright © 2015 Jannik Lorenz. All rights reserved.
//
import Foundation
import XLForm
import SwiftyJSON
class SingleLineViewController: XLFormViewController {
var line: Line?
var updateing = false
// MARK: Init
convenience init(line: Line){
self.init(nibName: nil, bundle: nil)
self.line = line
line.events.listenTo("setSession") { () -> () in
self.updateForm()
}
line.events.listenTo("setConfig") { () -> () in
self.updateForm()
}
line.events.listenTo("disconnect", action: { () -> () in
self.navigationController?.popViewControllerAnimated(true)
})
line.events.listenTo("error", action: { () -> () in
self.navigationController?.popViewControllerAnimated(true)
})
self.initializeForm()
}
// MARK: View Livestyle
override func viewDidLoad() {
super.viewDidLoad()
// if let session = line?.session {
// let f = Test_View(frame: CGRectMake(0, 0, view.frame.width, 500), session: session)
// view.addSubview(f)
// }
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.title = line?.title
self.updateForm()
}
// MARK: Form Creation
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
form = XLFormDescriptor()
section = XLFormSectionDescriptor() as XLFormSectionDescriptor
form.addFormSection(section)
section.title = "Modus"
// Disziplin
row = XLFormRowDescriptor(tag: "disziplin", rowType: XLFormRowDescriptorTypeSelectorActionSheet, title: "Disziplin")
section.addFormRow(row)
// Parts
row = XLFormRowDescriptor(tag: "part", rowType: XLFormRowDescriptorTypeSelectorActionSheet, title: "Part")
section.addFormRow(row)
section = XLFormSectionDescriptor() as XLFormSectionDescriptor
form.addFormSection(section)
section.title = "Nachricht"
// Nachricht
row = XLFormRowDescriptor(tag: "message", rowType: XLFormRowDescriptorTypeSelectorActionSheet, title: "Nachricht")
row.selectorOptions = [
XLFormOptionsObject(value: "sicherheit", displayText: "Sicherheit"),
XLFormOptionsObject(value: "pause", displayText: "Pause"),
]
section.addFormRow(row)
// Nachricht ausblenden
row = XLFormRowDescriptor(tag: "hideMessage", rowType: XLFormRowDescriptorTypeButton, title: "Nachricht ausblenden")
row.action.formBlock = { form in
self.tableView.selectRowAtIndexPath(nil, animated: true, scrollPosition: .None)
self.line?.hideMessage()
}
section.addFormRow(row)
self.form = form
self.tableView?.reloadData()
}
func updateForm(){
self.updateing = true
// Disziplin
var row = form.formRowWithTag("disziplin")
var disziplinenList: [XLFormOptionsObject] = []
if let groups = line?.config?["disziplinen"]["groups"].arrayValue {
for singleGroup in groups {
for disziplinID in singleGroup["disziplinen"].arrayValue {
let disziplin = line?.config?["disziplinen"]["all"][disziplinID.stringValue]
let option = XLFormOptionsObject(value: disziplinID.stringValue, displayText: disziplin?["title"].stringValue)
disziplinenList.append(option)
if (disziplinID.stringValue == line?.session?["disziplin"]["_id"].string) {
row?.value = option
}
}
}
}
row?.selectorOptions = disziplinenList
// Parts
row = form.formRowWithTag("part")
var partsList: [XLFormOptionsObject] = []
if let parts = line?.session?["disziplin"]["parts"].dictionaryValue {
for (key, part) in parts {
let option = XLFormOptionsObject(value: key, displayText: part["title"].stringValue)
partsList.append(option)
if (key == line?.session?["type"].string) {
row?.value = option
}
}
}
row?.selectorOptions = partsList
self.tableView?.reloadData()
self.updateing = false
}
override func formRowDescriptorValueHasChanged(formRow: XLFormRowDescriptor!, oldValue: AnyObject!, newValue: AnyObject!) {
if updateing {
return
}
switch (formRow.tag){
case "part"?:
if let option = formRow.value as? XLFormOptionsObject {
line?.setPart(option.valueData() as! String)
}
case "disziplin"?:
if let option = formRow.value as? XLFormOptionsObject {
line?.setDisziplin(option.valueData() as! String)
}
case "message"?:
if let option = formRow.value?.valueData() as? String {
switch (option){
case "sicherheit":
line?.showMessage("Sicherheit", type: Line.DSCAPIMethodMessage.danger)
case "pause":
line?.showMessage("Pause", type: Line.DSCAPIMethodMessage.black)
default:
break
}
formRow.value = nil
}
default:
break
}
}
class Test_View: UIView {
var session: JSON?
// override init(frame: CGRect) {
// super.init(frame: frame)
// }
//
// required init?(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
// }
convenience init(frame: CGRect, session: JSON){
self.init(frame: frame)
self.session = session
}
override func drawRect(rect: CGRect) {
let scheibe = session?["disziplin"]["scheibe"]
/*
var lastRing = scheibe.ringe[scheibe.ringe.length-1]
for (var i = scheibe.ringe.length-1; i >= 0; i--){
var ring = scheibe.ringe[i]
context.globalAlpha = 1.0
context.fillStyle = ring.color;
context.beginPath();
context.arc(lastRing.width/2*zoom.scale+zoom.offset.x, lastRing.width/2*zoom.scale+zoom.offset.y, ring.width/2*zoom.scale, 0, 2*Math.PI);
context.closePath();
context.fill();
context.strokeStyle = ring.textColor
context.lineWidth = 4;
context.stroke();
context.fillStyle = "black";
if (ring.text == true){
context.font = "bold "+(scheibe.text.size*zoom.scale)+"px verdana, sans-serif";
context.fillStyle = ring.textColor
context.fillText(ring.value, (lastRing.width/2 - ring.width/2 + scheibe.text.left)*zoom.scale+zoom.offset.x, (lastRing.width/2+scheibe.text.width)*zoom.scale+zoom.offset.y);
context.fillText(ring.value, (lastRing.width/2 + ring.width/2 + scheibe.text.right)*zoom.scale+zoom.offset.x, (lastRing.width/2+scheibe.text.width)*zoom.scale+zoom.offset.y);
context.fillText(ring.value, (lastRing.width/2-scheibe.text.width)*zoom.scale+zoom.offset.x, (lastRing.width/2 + ring.width/2 + scheibe.text.down)*zoom.scale+zoom.offset.y);
context.fillText(ring.value, (lastRing.width/2-scheibe.text.width)*zoom.scale+zoom.offset.x, (lastRing.width/2 - ring.width/2 + scheibe.text.up)*zoom.scale+zoom.offset.y);
}
}
*/
if let ringe = scheibe?["ringe"].arrayValue {
let lastRing = ringe.last
for ring in ringe {
print(ring)
// let radius = ring["width"].intValue/ 2*
var path = UIBezierPath(ovalInRect: CGRect(x: 0, y: 0, width: 300, height: 300))
UIColor.greenColor().setFill()
path.fill()
}
}
// let h = rect.height
// let w = rect.width
// var color:UIColor = UIColor.yellowColor()
//
// var drect = CGRect(x: (w * 0.25),y: (h * 0.25),width: (w * 0.5),height: (h * 0.5))
// var bpath:UIBezierPath = UIBezierPath(rect: drect)
// color.set()
// bpath.stroke()
}
}
}
| gpl-3.0 |
BanyaKrylov/Learn-Swift | Skill/Homework 9/Homework 9/SceneDelegate.swift | 2 | 2351 | //
// SceneDelegate.swift
// Homework 9
//
// Created by Ivan Krylov on 06.02.2020.
// Copyright © 2020 Ivan Krylov. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| apache-2.0 |
matsprea/omim | iphone/Maps/Core/Theme/BookmarksStyleSheet.swift | 1 | 864 | import Foundation
class BookmarksStyleSheet: IStyleSheet {
static func register(theme: Theme, colors: IColors, fonts: IFonts) {
theme.add(styleName: "BookmarksCategoryTextView") { (s) -> (Void) in
s.font = fonts.regular16
s.fontColor = colors.blackPrimaryText
s.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
theme.add(styleName: "BookmarksCategoryDeleteButton") { (s) -> (Void) in
s.font = fonts.regular17
s.fontColor = colors.red
s.fontColorDisabled = colors.blackHintText
}
theme.add(styleName: "BookmarksActionCreateIcon") { (s) -> (Void) in
s.tintColor = colors.linkBlue
}
theme.add(styleName: "BookmarkSharingLicense", from: "TermsOfUseLinkText") { (s) -> (Void) in
s.fontColor = colors.blackSecondaryText
s.font = fonts.regular14
}
}
}
| apache-2.0 |
P0ed/FireTek | Source/SpaceEngine/Systems/WeaponSystem.swift | 1 | 3203 | import SpriteKit
import PowerCore
import Fx
struct WeaponSystem {
private let world: World
private var primaryFiringEntities = [] as Set<Entity>
private var secondaryFiringEntities = [] as Set<Entity>
init(world: World) {
self.world = world
}
mutating func update() {
applyShipsInputs()
updateCooldowns()
primaryFiringEntities = updateFiring(firing: primaryFiringEntities, weapons: world.primaryWpn)
secondaryFiringEntities = updateFiring(firing: secondaryFiringEntities, weapons: world.secondaryWpn)
}
private mutating func applyShipsInputs() {
let ships = world.ships
let inputs = world.shipInput
let primaryWpn = world.primaryWpn
let secondaryWpn = world.secondaryWpn
ships.enumerated().forEach { index, ship in
let entity = ships.entityAt(index)
let input = inputs[ship.input]
if input.primaryFire && primaryWpn[ship.primaryWpn].remainingCooldown == 0 {
primaryFiringEntities.insert(entity)
}
if input.secondaryFire && secondaryWpn[ship.secondaryWpn].remainingCooldown == 0 {
secondaryFiringEntities.insert(entity)
}
}
}
private func updateCooldowns() {
for index in world.primaryWpn.indices {
updateWeaponCooldown(&world.primaryWpn[index])
}
for index in world.secondaryWpn.indices {
updateWeaponCooldown(&world.secondaryWpn[index])
}
}
private func updateWeaponCooldown(_ weapon: inout WeaponComponent) {
if weapon.remainingCooldown != 0 {
weapon.remainingCooldown = max(0, weapon.remainingCooldown - Float(SpaceEngine.timeStep))
if weapon.remainingCooldown == 0 && weapon.rounds == 0 {
weapon.rounds = min(weapon.roundsPerShot, weapon.ammo)
}
}
}
private func updateFiring(firing: Set<Entity>, weapons: Store<WeaponComponent>) -> Set<Entity> {
return firing.filterSet { entity in
if let index = weapons.indexOf(entity) {
let weapon = weapons[index]
if weapon.remainingCooldown == 0 && weapon.rounds != 0 {
let offset = CGVector(dx: 0, dy: 36)
if let spriteIndex = world.sprites.indexOf(entity) {
let transform = world.sprites[spriteIndex].sprite.transform.move(by: offset)
fire(&weapons[index], at: transform, source: entity)
}
else {
return false
}
}
return weapons[index].rounds > 0
}
else {
return false
}
}
}
private func fire(_ weapon: inout WeaponComponent, at transform: Transform, source: Entity) {
let roundsPerTick = weapon.perShotCooldown == 0 ? weapon.rounds : 1
weapon.rounds -= roundsPerTick
weapon.ammo -= roundsPerTick
weapon.remainingCooldown += weapon.rounds == 0 ? weapon.cooldown : weapon.perShotCooldown
for round in 0..<roundsPerTick {
ProjectileFactory.createProjectile(
world,
at: transform.move(by: offset(round: round, outOf: roundsPerTick)),
velocity: weapon.velocity,
projectile: ProjectileComponent(
source: source,
type: weapon.type,
damage: weapon.damage
)
)
}
}
private func offset(round: Int, outOf total: Int) -> CGVector {
if total == 1 { return .zero }
let spacing = 4 as CGFloat
let spread = spacing * CGFloat(total - 1)
return CGVector(
dx: (-spread / 2) + spacing * CGFloat(round),
dy: 0
)
}
}
| mit |
juslee/fabric-sdk-swift | Sources/Hfc/protocols/CryptoSuiteProtocol.swift | 1 | 583 | protocol CryptoSuiteProtocol {
func generateKey(opts: Any) -> KeyProtocol
func deriveKey(key: KeyProtocol, opts: Any) -> KeyProtocol
func importKey(raw: [UInt8], opts: Any) -> KeyProtocol
func getKey(ski: [UInt8]) -> KeyProtocol
func hash(msg: [UInt8], opts: Any) -> String
func sign(key: KeyProtocol, digest: [UInt8], opts: Any) -> [UInt8]
func verify(key: KeyProtocol, signature: [UInt8], digest: [UInt8]) -> Bool
func encrypt(key: KeyProtocol, plainText: [UInt8], opts: Any) -> [UInt8]
func decrypt(key: KeyProtocol, cipherText: [UInt8], opts: Any) -> [UInt8]
}
| apache-2.0 |
Eonil/EditorLegacy | Modules/Editor/Tests/main.swift | 1 | 233 | //
// main.swift
// UnitTests
//
// Created by Hoon H. on 2015/01/11.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Foundation
struct UnitTest {
func runAll() {
testDiff()
}
}
let ut = UnitTest()
ut.runAll() | mit |
retsohuang/RHMVVMHelpers | RHMVVMHelpers/ViewController.swift | 1 | 895 | //
// ViewController.swift
// RHMVVMHelpers
//
// Created by Retso Huang on 12/29/14.
// Copyright (c) 2014 Retso Huang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: - Layout
@IBOutlet weak var label: UILabel!
@IBOutlet weak var secondLabel: UILabel!
// MARK: - Variable
var text = Dynamic("")
override func viewDidLoad() {
super.viewDidLoad()
/**
* Binding with text variable and set value
*/
self.text.bindAndFire {
self.label.text = $0
}
/**
* Binding with text variable
*/
self.text.bind {
self.secondLabel.text = $0
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MAKR: - User Control Event
@IBAction func textFieldEditingChanged(sender: UITextField) {
self.text.value = sender.text
}
}
| mit |
koba-uy/chivia-app-ios | src/Pods/MapboxCoreNavigation/MapboxCoreNavigation/SpokenInstructionFormatter.swift | 1 | 9539 | import Foundation
import CoreLocation
import OSRMTextInstructions
/**
Formatter for creating speech strings.
*/
@objc(MBSpokenInstructionFormatter)
public class SpokenInstructionFormatter: NSObject {
let routeStepFormatter = RouteStepFormatter()
let maneuverVoiceDistanceFormatter = SpokenDistanceFormatter(approximate: true)
public override init() {
maneuverVoiceDistanceFormatter.unitStyle = .long
maneuverVoiceDistanceFormatter.numberFormatter.locale = .nationalizedCurrent
}
/**
Creates a string used for announcing a step.
If `markUpWithSSML` is true, the string will contain [SSML](https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference). Your speech synthesizer should accept this type of string. See `PolleyVoiceController`.
*/
public func string(routeProgress: RouteProgress, userDistance: CLLocationDistance, markUpWithSSML: Bool) -> String {
let alertLevel = routeProgress.currentLegProgress.alertUserLevel
let escapeIfNecessary = {(distance: String) -> String in
return markUpWithSSML ? distance.addingXMLEscapes : distance
}
// If the current step arrives at a waypoint, the upcoming step is part of the next leg.
let upcomingLegIndex = routeProgress.currentLegProgress.currentStep.maneuverType == .arrive ? routeProgress.legIndex + 1 :routeProgress.legIndex
// Even if the next waypoint and the waypoint after that have the same coordinates, there will still be a step in between the two arrival steps. So the upcoming and follow-on steps are guaranteed to be part of the same leg.
let followOnLegIndex = upcomingLegIndex
// Handle arriving at the final destination
//
let numberOfLegs = routeProgress.route.legs.count
guard let followOnInstruction = routeStepFormatter.string(for: routeProgress.currentLegProgress.followOnStep, legIndex: followOnLegIndex, numberOfLegs: numberOfLegs, markUpWithSSML: markUpWithSSML) else {
let upComingStepInstruction = routeStepFormatter.string(for: routeProgress.currentLegProgress.upComingStep, legIndex: upcomingLegIndex, numberOfLegs: numberOfLegs, markUpWithSSML: markUpWithSSML)!
var text: String
if alertLevel == .arrive {
text = upComingStepInstruction
} else {
let phrase = escapeIfNecessary(routeStepFormatter.instructions.phrase(named: .instructionWithDistance))
text = phrase.replacingTokens { (tokenType) -> String in
switch tokenType {
case .firstInstruction:
return upComingStepInstruction
case .distance:
return escapeIfNecessary(maneuverVoiceDistanceFormatter.string(from: userDistance))
default:
fatalError("Unexpected token \(tokenType)")
}
}
}
return text
}
// If there is no `upComingStep`, there definitely should not be a followOnStep.
// This should be caught above.
let upComingInstruction = routeStepFormatter.string(for: routeProgress.currentLegProgress.upComingStep, legIndex: upcomingLegIndex, numberOfLegs: numberOfLegs, markUpWithSSML: markUpWithSSML)!
let upcomingStepDuration = routeProgress.currentLegProgress.upComingStep!.expectedTravelTime
let currentInstruction = routeStepFormatter.string(for: routeProgress.currentLegProgress.currentStep, legIndex: routeProgress.legIndex, numberOfLegs: numberOfLegs, markUpWithSSML: markUpWithSSML)
let step = routeProgress.currentLegProgress.currentStep
var text: String
// Prevent back to back instructions by adding a little more wiggle room
let linkedInstructionMultiplier = RouteControllerHighAlertInterval * RouteControllerLinkedInstructionBufferMultiplier
// We only want to announce this special depature announcement once.
// Once it has been announced, all subsequnt announcements will not have an alert level of low
// since the user will be approaching the maneuver location.
let isStartingDeparture = routeProgress.currentLegProgress.currentStep.maneuverType == .depart && (alertLevel == .depart || alertLevel == .low)
if let currentInstruction = currentInstruction, isStartingDeparture {
if routeProgress.currentLegProgress.currentStep.distance > RouteControllerMinimumDistanceForContinueInstruction {
text = currentInstruction
} else if upcomingStepDuration > linkedInstructionMultiplier {
// If the upcoming step is an .exitRoundabout or .exitRotary, don't link the instruction
if let followOnStep = routeProgress.currentLegProgress.followOnStep, followOnStep.maneuverType == .exitRoundabout || followOnStep.maneuverType == .exitRotary {
text = upComingInstruction
} else {
let phrase = escapeIfNecessary(routeStepFormatter.instructions.phrase(named: .twoInstructionsWithDistance))
text = phrase.replacingTokens { (tokenType) -> String in
switch tokenType {
case .firstInstruction:
return currentInstruction
case .secondInstruction:
return upComingInstruction
case .distance:
return maneuverVoiceDistanceFormatter.string(from: userDistance)
default:
fatalError("Unexpected token \(tokenType)")
}
}
}
} else {
text = upComingInstruction
}
} else if routeProgress.currentLegProgress.currentStep.distance > RouteControllerMinimumDistanceForContinueInstruction && routeProgress.currentLegProgress.alertUserLevel == .low {
if isStartingDeparture && upcomingStepDuration < linkedInstructionMultiplier {
let phrase = escapeIfNecessary(routeStepFormatter.instructions.phrase(named: .twoInstructionsWithDistance))
text = phrase.replacingTokens { (tokenType) -> String in
switch tokenType {
case .firstInstruction:
return currentInstruction!
case .secondInstruction:
return upComingInstruction
case .distance:
return escapeIfNecessary(maneuverVoiceDistanceFormatter.string(from: userDistance))
default:
fatalError("Unexpected token \(tokenType)")
}
}
} else if let roadDescription = step.roadDescription(markedUpWithSSML: markUpWithSSML) {
text = String.localizedStringWithFormat(NSLocalizedString("CONTINUE_ON_ROAD", bundle: .mapboxCoreNavigation, value: "Continue on %@ for %@", comment: "Format for speech string after completing a maneuver and starting a new step; 1 = way name; 2 = distance"), roadDescription, escapeIfNecessary(maneuverVoiceDistanceFormatter.string(from: userDistance)))
} else {
text = String.localizedStringWithFormat(NSLocalizedString("CONTINUE", bundle: .mapboxCoreNavigation, value: "Continue for %@", comment: "Format for speech string after completing a maneuver and starting a new step; 1 = distance"), escapeIfNecessary(maneuverVoiceDistanceFormatter.string(from: userDistance)))
}
} else if alertLevel == .high && upcomingStepDuration < linkedInstructionMultiplier {
// If the upcoming step is an .exitRoundabout or .exitRotary, don't link the instruction
if let followOnStep = routeProgress.currentLegProgress.followOnStep, followOnStep.maneuverType == .exitRoundabout || followOnStep.maneuverType == .exitRotary {
text = upComingInstruction
} else {
let phrase = escapeIfNecessary(routeStepFormatter.instructions.phrase(named: .twoInstructions))
text = phrase.replacingTokens { (tokenType) -> String in
switch tokenType {
case .firstInstruction:
return upComingInstruction
case .secondInstruction:
return followOnInstruction
default:
fatalError("Unexpected token \(tokenType)")
}
}
}
} else if alertLevel != .high {
let phrase = escapeIfNecessary(routeStepFormatter.instructions.phrase(named: .instructionWithDistance))
text = phrase.replacingTokens { (tokenType) -> String in
switch tokenType {
case .firstInstruction:
return upComingInstruction
case .distance:
return escapeIfNecessary(maneuverVoiceDistanceFormatter.string(from: userDistance))
default:
fatalError("Unexpected token \(tokenType)")
}
}
} else {
text = upComingInstruction
}
return text.removingPunctuation
}
}
| lgpl-3.0 |
benlangmuir/swift | validation-test/compiler_crashers_fixed/26746-swift-parser-skipsingle.swift | 65 | 495 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
{
{let[{{
{
[[{
({
{((((({
[{
{
{{
{{
{{[({({
{{{{{
{((
{
{{
{
{
{
{("
}
}if{
let d{
class
case,
| apache-2.0 |
miller-ms/ViewAnimator | ViewAnimator/SpringAnimatorConroller.swift | 1 | 6745 | //
// SpringAnimatorConroller.swift
// ViewAnimator
//
// Created by William Miller DBA Miller Mobilesoft on 5/13/17.
//
// This application is intended to be a developer tool for evaluating the
// options for creating an animation or transition using the UIView static
// methods UIView.animate and UIView.transition.
// Copyright © 2017 William Miller DBA Miller Mobilesoft
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// If you would like to reach the developer you may email me at
// support@millermobilesoft.com or visit my website at
// http://millermobilesoft.com
//
import UIKit
class SpringAnimatorConroller: AnimatorController {
enum ParamCellIdentifiers:Int {
case durationCell = 0
case delayCell
case springDampingCell
case velocityCell
case optionsCell
case propertiesCell
case count
}
enum SpringAnimateCellIdentifiers:Int {
case animateCell = 0
case count
}
enum SectionIdentifiers:Int {
case animateSection = 0
case parameterSection
case count
}
var duration = Double(1.0)
var delay = Double(0.25)
var springDamping = CGFloat(0.5)
var velocity = CGFloat(0.5)
var animationProperties = PropertiesModel()
var options = OptionsModel(options: [UIViewAnimationOptions.curveEaseInOut])
override func viewDidLoad() {
super.viewDidLoad()
cellIdentifiers = [ "SpringAnimationCellId", "DurationCellId", "DelayCellId", "SpringDampingCellId", "SpringVelocityCellId", "OptionsCellId", "PropertiesCellId"]
sectionHeaderTitles = ["Spring Animation", "Parameters"]
identifierBaseIdx = [0,
SpringAnimateCellIdentifiers.count.rawValue]
sectionCount = [SpringAnimateCellIdentifiers.count.rawValue, ParamCellIdentifiers.count.rawValue]
rowHeights = [CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0)]
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func saveParameters () {
var parameterPath = IndexPath(row:ParamCellIdentifiers.durationCell.rawValue, section: SectionIdentifiers.parameterSection.rawValue)
var cell = tableView.cellForRow(at: parameterPath) as? FloatValueCell
if cell != nil {
duration = Double(cell!.value)
}
parameterPath = IndexPath(row:ParamCellIdentifiers.delayCell.rawValue, section: SectionIdentifiers.parameterSection.rawValue)
cell = tableView.cellForRow(at: parameterPath) as? FloatValueCell
if cell != nil {
delay = Double(cell!.value)
}
parameterPath = IndexPath(row:ParamCellIdentifiers.springDampingCell.rawValue, section: SectionIdentifiers.parameterSection.rawValue)
cell = tableView.cellForRow(at: parameterPath) as? FloatValueCell
if cell != nil {
springDamping = CGFloat(cell!.value)
}
parameterPath = IndexPath(row:ParamCellIdentifiers.velocityCell.rawValue, section: SectionIdentifiers.parameterSection.rawValue)
cell = tableView.cellForRow(at: parameterPath) as? FloatValueCell
if cell != nil {
velocity = CGFloat(cell!.value)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let section = SectionIdentifiers(rawValue: indexPath.section) else {
return
}
let cell = tableView.cellForRow(at: indexPath)!
cell.isSelected = false
switch section {
case .animateSection:
let curveCell = cell as! SpringAnimationCell
curveCell.reset()
default:
break
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination is PropertiesController {
let propertiesVC = segue.destination as! PropertiesController
propertiesVC.animationProperties = animationProperties
} else if segue.destination is SpringOptionsController {
let optionsVC = segue.destination as! SpringOptionsController
optionsVC.options = options
}
}
@IBAction func durationChanged(_ sender: UISlider) {
let cell = sender.superview!.superview as! FloatValueCell
duration = Double(cell.value)
}
@IBAction func delayChanged(_ sender: UISlider) {
let cell = sender.superview?.superview as! FloatValueCell
delay = Double(cell.value)
}
@IBAction func springDampingChanged(_ sender: UISlider) {
let cell = sender.superview!.superview as! FloatValueCell
springDamping = CGFloat(cell.value)
}
@IBAction func springVelocityChanged(_ sender: UISlider) {
let cell = sender.superview!.superview as! FloatValueCell
velocity = CGFloat(cell.value)
}
@IBAction func executeSpringAnimation(_ sender: UIButton) {
let cell = sender.superview?.superview as! SpringAnimationCell
let hex = String(format: "%x", options.animationOptions.rawValue) // SpringOptionsController.springOptions.rawValue)
print("Options for animate are \(hex)")
saveParameters()
cell.executeAnimation(withDuration: duration, andDelay: delay, usingSpringwithDamping: springDamping, withInitialSpringVelocity: velocity, animationOptions: options.animationOptions, animationProperties: animationProperties)
}
}
| gpl-3.0 |
EasySwift/EasySwift | Carthage/Checkouts/Bond/BondTests/ProtocolProxyTests.swift | 4 | 2253 | //
// ProtocolProxyTests.swift
// Bond
//
// Created by Srdan Rasic on 29/08/16.
// Copyright © 2016 Swift Bond. All rights reserved.
//
import XCTest
import ReactiveKit
@testable import Bond
@objc protocol TestDelegate {
func methodA()
func methodB(_ object: TestObject)
func methodC(_ object: TestObject, value: Int)
func methodD(_ object: TestObject, value: Int) -> NSString
}
class TestObject: NSObject {
weak var delegate: TestDelegate! = nil
override init() {
super.init()
}
func callMethodA() {
delegate.methodA()
}
func callMethodB() {
delegate.methodB(self)
}
func callMethodC(_ value: Int) {
delegate.methodC(self, value: value)
}
func callMethodD(_ value: Int) -> NSString {
return delegate.methodD(self, value: value)
}
}
class ProtocolProxyTests: XCTestCase {
var object: TestObject! = nil
var delegate: ProtocolProxy {
return object.protocolProxy(for: TestDelegate.self, setter: NSSelectorFromString("setDelegate:"))
}
override func setUp() {
object = TestObject()
}
func testCallbackA() {
let stream = delegate.signal(for: #selector(TestDelegate.methodA)) { (stream: PublishSubject1<Int>) in
stream.next(0)
}
stream.expectNext([0, 0])
object.callMethodA()
object.callMethodA()
}
func testCallbackB() {
let stream = delegate.signal(for: #selector(TestDelegate.methodB(_:))) { (stream: PublishSubject1<Int>, _: TestObject) in
stream.next(0)
}
stream.expectNext([0, 0])
object.callMethodB()
object.callMethodB()
}
func testCallbackC() {
let stream = delegate.signal(for: #selector(TestDelegate.methodC(_:value:))) { (stream: PublishSubject1<Int>, _: TestObject, value: Int) in
stream.next(value)
}
stream.expectNext([10, 20])
object.callMethodC(10)
object.callMethodC(20)
}
func testCallbackD() {
let stream = delegate.signal(for: #selector(TestDelegate.methodD(_:value:))) { (stream: PublishSubject1<Int>, _: TestObject, value: Int) -> NSString in
stream.next(value)
return "\(value)" as NSString
}
stream.expectNext([10, 20])
XCTAssertEqual(object.callMethodD(10), "10")
XCTAssertEqual(object.callMethodD(20), "20")
}
}
| apache-2.0 |
hanhailong/practice-swift | Views/NavigationBar/SegmentedControl as button in the NavigationBar/SegmentedControl as button in the NavigationBar/ViewController.swift | 2 | 922 | //
// ViewController.swift
// SegmentedControl as button in the NavigationBar
//
// Created by Domenico Solazzo on 06/05/15.
// License MIT
//
import UIKit
class ViewController: UIViewController {
let items = ["Up", "Down"]
func segmentedControlValueChanged(sender: UISegmentedControl){
if (sender.selectedSegmentIndex < items.count){
println(items[sender.selectedSegmentIndex])
}else{
println("Unknown button")
}
}
override func viewDidLoad() {
super.viewDidLoad()
var segmentedControl = UISegmentedControl(items: items)
segmentedControl.momentary = true
segmentedControl.addTarget(self, action: "segmentedControlValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: segmentedControl)
}
}
| mit |
calebkleveter/BluetoothKit | Source/BKScanner.swift | 1 | 4397 | //
// BluetoothKit
//
// Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import CoreBluetooth
internal class BKScanner: BKCBCentralManagerDiscoveryDelegate {
// MARK: Type Aliases
internal typealias ScanCompletionHandler = ((_ result: [BKDiscovery]?, _ error: BKError?) -> Void)
// MARK: Enums
internal enum BKError: Error {
case noCentralManagerSet
case busy
case interrupted
}
// MARK: Properties
internal var configuration: BKConfiguration!
internal var centralManager: CBCentralManager!
private var busy = false
private var scanHandlers: (progressHandler: BKCentral.ScanProgressHandler?, completionHandler: ScanCompletionHandler )?
private var discoveries = [BKDiscovery]()
private var durationTimer: Timer?
// MARK: Internal Functions
internal func scanWithDuration(_ duration: TimeInterval, progressHandler: BKCentral.ScanProgressHandler? = nil, completionHandler: @escaping ScanCompletionHandler) throws {
do {
try validateForActivity()
busy = true
scanHandlers = ( progressHandler: progressHandler, completionHandler: completionHandler)
centralManager.scanForPeripherals(withServices: configuration.serviceUUIDs, options: nil)
durationTimer = Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(BKScanner.durationTimerElapsed), userInfo: nil, repeats: false)
} catch let error {
throw error
}
}
internal func interruptScan() {
guard busy else {
return
}
endScan(.interrupted)
}
// MARK: Private Functions
private func validateForActivity() throws {
guard !busy else {
throw BKError.busy
}
guard centralManager != nil else {
throw BKError.noCentralManagerSet
}
}
@objc private func durationTimerElapsed() {
endScan(nil)
}
private func endScan(_ error: BKError?) {
invalidateTimer()
centralManager.stopScan()
let completionHandler = scanHandlers?.completionHandler
let discoveries = self.discoveries
scanHandlers = nil
self.discoveries.removeAll()
busy = false
completionHandler?(discoveries, error)
}
private func invalidateTimer() {
if let durationTimer = self.durationTimer {
durationTimer.invalidate()
self.durationTimer = nil
}
}
// MARK: BKCBCentralManagerDiscoveryDelegate
internal func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
guard busy else {
return
}
let RSSI = Int(RSSI)
let remotePeripheral = BKRemotePeripheral(identifier: peripheral.identifier, peripheral: peripheral)
remotePeripheral.configuration = configuration
let discovery = BKDiscovery(advertisementData: advertisementData, remotePeripheral: remotePeripheral, RSSI: RSSI)
if !discoveries.contains(discovery) {
discoveries.append(discovery)
scanHandlers?.progressHandler?([ discovery ])
}
}
}
| mit |
justinlevi/asymptotik-rnd-scenekit-kaleidoscope | Atk_Rnd_VisualToys/ScreenTextureQuad.swift | 2 | 4211 | //
// quadVertexBuffer.swift
// Atk_Rnd_VisualToys
//
// Created by Rick Boykin on 9/30/14.
// Copyright (c) 2014 Asymptotik Limited. All rights reserved.
//
import Foundation
import OpenGLES
class ScreenTextureQuad {
var vertexBufferObject:GLuint = 0
var normalBufferObject:GLuint = 0
var indexBufferObject:GLuint = 0
var positionIndex:GLuint = 0
var textureCoordinateIndex:GLuint = 0
var textureUniformIndex:GLuint = 0
var glProgram:GLProgram? = nil;
init() {
}
var min:GLfloat = -1.0
var max:GLfloat = 1.0
func initialize() {
let verts:[GLfloat] = [
min, max, 0, // vert
0, 0, 1, // norm
0, 1, // tex
min, min, 0,
0, 0, 1,
0, 0,
max, max, 0,
0, 0, 1,
1, 1,
max, min, 0,
0, 0, 1,
1, 0
]
let indices:[GLushort] = [
0, 1, 2, 2, 1, 3
]
let ptr = UnsafePointer<GLfloat>(bitPattern: 0)
self.glProgram = GLProgram(vertexShaderFilename: "PassthroughShader", fragmentShaderFilename: "PassthroughShader")
self.glProgram!.addAttribute("position")
self.positionIndex = self.glProgram!.attributeIndex("position")
self.glProgram!.addAttribute("textureCoordinate")
self.textureCoordinateIndex = self.glProgram!.attributeIndex("textureCoordinate")
self.glProgram!.link()
self.textureUniformIndex = self.glProgram!.uniformIndex("textureUnit")
// Create the buffer objects
glGenBuffers(1, &vertexBufferObject)
glGenBuffers(1, &indexBufferObject)
// Copy data to video memory
// Vertex data
glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexBufferObject)
glBufferData(GLenum(GL_ARRAY_BUFFER), sizeof(GLfloat)*verts.count, verts, GLenum(GL_STATIC_DRAW))
glEnableVertexAttribArray(self.positionIndex)
glVertexAttribPointer(self.positionIndex, GLint(3), GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(sizeof(GLfloat) * 8), ptr)
glEnableVertexAttribArray(self.textureCoordinateIndex)
glVertexAttribPointer(self.textureCoordinateIndex, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(sizeof(GLfloat) * 8), ptr.advancedBy(6))
// Indexes
glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), indexBufferObject)
glBufferData(GLenum(GL_ELEMENT_ARRAY_BUFFER), sizeof(GLushort) * indices.count, indices, GLenum(GL_STATIC_DRAW))
}
func draw(target:GLenum, name:GLuint) {
glActiveTexture(GLenum(GL_TEXTURE0))
glEnable(target)
glBindTexture(target, name)
glUniform1i(GLint(self.textureUniformIndex), 0)
self.glProgram!.use()
// bind VBOs for vertex array and index array
// for vertex coordinates
let ptr = UnsafePointer<GLfloat>(bitPattern: 0)
glBindBuffer(GLenum(GL_ARRAY_BUFFER), self.vertexBufferObject)
glEnableVertexAttribArray(self.positionIndex)
glVertexAttribPointer(self.positionIndex, GLint(3), GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(sizeof(GLfloat) * 8), ptr)
glEnableVertexAttribArray(self.textureCoordinateIndex)
glVertexAttribPointer(self.textureCoordinateIndex, GLint(2), GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(sizeof(GLfloat) * 8), ptr.advancedBy(6))
// Indices
glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), self.indexBufferObject) // for indices
// draw 2 triangle (6 indices) using offset of index array
glDrawElements(GLenum(GL_TRIANGLES), GLsizei(6), GLenum(GL_UNSIGNED_SHORT), ptr)
// bind with 0, so, switch back to normal pointer operation
glDisableVertexAttribArray(self.positionIndex)
glDisableVertexAttribArray(self.textureCoordinateIndex)
glBindBuffer(GLenum(GL_ARRAY_BUFFER), 0)
glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), 0)
}
} | mit |
joshdholtz/fastlane | fastlane/swift/DeliverfileProtocol.swift | 2 | 9492 | protocol DeliverfileProtocol: class {
/// Your Apple ID Username
var username: String { get }
/// The bundle identifier of your app
var appIdentifier: String? { get }
/// The version that should be edited or created
var appVersion: String? { get }
/// Path to your ipa file
var ipa: String? { get }
/// Path to your pkg file
var pkg: String? { get }
/// If set the given build number (already uploaded to iTC) will be used instead of the current built one
var buildNumber: String? { get }
/// The platform to use (optional)
var platform: String { get }
/// Modify live metadata, this option disables ipa upload and screenshot upload
var editLive: Bool { get }
/// Force usage of live version rather than edit version
var useLiveVersion: Bool { get }
/// Path to the folder containing the metadata files
var metadataPath: String? { get }
/// Path to the folder containing the screenshots
var screenshotsPath: String? { get }
/// Skip uploading an ipa or pkg to App Store Connect
var skipBinaryUpload: Bool { get }
/// Don't upload the screenshots
var skipScreenshots: Bool { get }
/// Don't upload the metadata (e.g. title, description). This will still upload screenshots
var skipMetadata: Bool { get }
/// Don't update app version for submission
var skipAppVersionUpdate: Bool { get }
/// Skip the HTML report file verification
var force: Bool { get }
/// Clear all previously uploaded screenshots before uploading the new ones
var overwriteScreenshots: Bool { get }
/// Submit the new version for Review after uploading everything
var submitForReview: Bool { get }
/// Rejects the previously submitted build if it's in a state where it's possible
var rejectIfPossible: Bool { get }
/// Should the app be automatically released once it's approved?
var automaticRelease: Bool { get }
/// Date in milliseconds for automatically releasing on pending approval
var autoReleaseDate: String? { get }
/// Enable the phased release feature of iTC
var phasedRelease: Bool { get }
/// Reset the summary rating when you release a new version of the application
var resetRatings: Bool { get }
/// The price tier of this application
var priceTier: String? { get }
/// Path to the app rating's config
var appRatingConfigPath: String? { get }
/// Extra information for the submission (e.g. compliance specifications, IDFA settings)
var submissionInformation: String? { get }
/// The ID of your App Store Connect team if you're in multiple teams
var teamId: String? { get }
/// The name of your App Store Connect team if you're in multiple teams
var teamName: String? { get }
/// The short ID of your Developer Portal team, if you're in multiple teams. Different from your iTC team ID!
var devPortalTeamId: String? { get }
/// The name of your Developer Portal team if you're in multiple teams
var devPortalTeamName: String? { get }
/// The provider short name to be used with the iTMSTransporter to identify your team. This value will override the automatically detected provider short name. To get provider short name run `pathToXcode.app/Contents/Applications/Application\ Loader.app/Contents/itms/bin/iTMSTransporter -m provider -u 'USERNAME' -p 'PASSWORD' -account_type itunes_connect -v off`. The short names of providers should be listed in the second column
var itcProvider: String? { get }
/// Run precheck before submitting to app review
var runPrecheckBeforeSubmit: Bool { get }
/// The default precheck rule level unless otherwise configured
var precheckDefaultRuleLevel: String { get }
/// An array of localized metadata items to upload individually by language so that errors can be identified. E.g. ['name', 'keywords', 'description']. Note: slow
var individualMetadataItems: [String] { get }
/// Metadata: The path to the app icon
var appIcon: String? { get }
/// Metadata: The path to the Apple Watch app icon
var appleWatchAppIcon: String? { get }
/// Metadata: The copyright notice
var copyright: String? { get }
/// Metadata: The english name of the primary category (e.g. `Business`, `Books`)
var primaryCategory: String? { get }
/// Metadata: The english name of the secondary category (e.g. `Business`, `Books`)
var secondaryCategory: String? { get }
/// Metadata: The english name of the primary first sub category (e.g. `Educational`, `Puzzle`)
var primaryFirstSubCategory: String? { get }
/// Metadata: The english name of the primary second sub category (e.g. `Educational`, `Puzzle`)
var primarySecondSubCategory: String? { get }
/// Metadata: The english name of the secondary first sub category (e.g. `Educational`, `Puzzle`)
var secondaryFirstSubCategory: String? { get }
/// Metadata: The english name of the secondary second sub category (e.g. `Educational`, `Puzzle`)
var secondarySecondSubCategory: String? { get }
/// Metadata: A hash containing the trade representative contact information
var tradeRepresentativeContactInformation: [String : Any]? { get }
/// Metadata: A hash containing the review information
var appReviewInformation: [String : Any]? { get }
/// Metadata: Path to the app review attachment file
var appReviewAttachmentFile: String? { get }
/// Metadata: The localised app description
var description: String? { get }
/// Metadata: The localised app name
var name: String? { get }
/// Metadata: The localised app subtitle
var subtitle: [String : Any]? { get }
/// Metadata: An array of localised keywords
var keywords: [String : Any]? { get }
/// Metadata: An array of localised promotional texts
var promotionalText: [String : Any]? { get }
/// Metadata: Localised release notes for this version
var releaseNotes: String? { get }
/// Metadata: Localised privacy url
var privacyUrl: String? { get }
/// Metadata: Localised Apple TV privacy policy text
var appleTvPrivacyPolicy: String? { get }
/// Metadata: Localised support url
var supportUrl: String? { get }
/// Metadata: Localised marketing url
var marketingUrl: String? { get }
/// Metadata: List of languages to activate
var languages: [String]? { get }
/// Ignore errors when invalid languages are found in metadata and screenshot directories
var ignoreLanguageDirectoryValidation: Bool { get }
/// Should precheck check in-app purchases?
var precheckIncludeInAppPurchases: Bool { get }
/// The (spaceship) app ID of the app you want to use/modify
var app: String { get }
}
extension DeliverfileProtocol {
var username: String { return "" }
var appIdentifier: String? { return nil }
var appVersion: String? { return nil }
var ipa: String? { return nil }
var pkg: String? { return nil }
var buildNumber: String? { return nil }
var platform: String { return "ios" }
var editLive: Bool { return false }
var useLiveVersion: Bool { return false }
var metadataPath: String? { return nil }
var screenshotsPath: String? { return nil }
var skipBinaryUpload: Bool { return false }
var skipScreenshots: Bool { return false }
var skipMetadata: Bool { return false }
var skipAppVersionUpdate: Bool { return false }
var force: Bool { return false }
var overwriteScreenshots: Bool { return false }
var submitForReview: Bool { return false }
var rejectIfPossible: Bool { return false }
var automaticRelease: Bool { return false }
var autoReleaseDate: String? { return nil }
var phasedRelease: Bool { return false }
var resetRatings: Bool { return false }
var priceTier: String? { return nil }
var appRatingConfigPath: String? { return nil }
var submissionInformation: String? { return nil }
var teamId: String? { return nil }
var teamName: String? { return nil }
var devPortalTeamId: String? { return nil }
var devPortalTeamName: String? { return nil }
var itcProvider: String? { return nil }
var runPrecheckBeforeSubmit: Bool { return true }
var precheckDefaultRuleLevel: String { return "warn" }
var individualMetadataItems: [String] { return [] }
var appIcon: String? { return nil }
var appleWatchAppIcon: String? { return nil }
var copyright: String? { return nil }
var primaryCategory: String? { return nil }
var secondaryCategory: String? { return nil }
var primaryFirstSubCategory: String? { return nil }
var primarySecondSubCategory: String? { return nil }
var secondaryFirstSubCategory: String? { return nil }
var secondarySecondSubCategory: String? { return nil }
var tradeRepresentativeContactInformation: [String : Any]? { return nil }
var appReviewInformation: [String : Any]? { return nil }
var appReviewAttachmentFile: String? { return nil }
var description: String? { return nil }
var name: String? { return nil }
var subtitle: [String : Any]? { return nil }
var keywords: [String : Any]? { return nil }
var promotionalText: [String : Any]? { return nil }
var releaseNotes: String? { return nil }
var privacyUrl: String? { return nil }
var appleTvPrivacyPolicy: String? { return nil }
var supportUrl: String? { return nil }
var marketingUrl: String? { return nil }
var languages: [String]? { return nil }
var ignoreLanguageDirectoryValidation: Bool { return false }
var precheckIncludeInAppPurchases: Bool { return true }
var app: String { return "" }
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.18]
| mit |
lakesoft/LKUserDefaultOption | Pod/Classes/LKUserDefaultOptionStepper.swift | 1 | 1011 | //
// LKUserDefaultOptionX.swift
// Pods
//
// Created by Hiroshi Hashiguchi on 2015/10/11.
//
//
public class LKUserDefaultOptionStepper:LKUserDefaultOption {
public var optionValue:Double = 0
public var minimumValue: Double = 0
public var maximumValue: Double = 10.0
public var stepValue: Double = 1.0
// MARK: - LKUserDefaultOptionModel
public override func save() {
saveUserDefaults(optionValue)
}
public override func restore() {
if let value = restoreUserDefaults() as? Double {
optionValue = value
}
}
public override func setValue(value:AnyObject) {
if let value = value as? Double {
optionValue = value
}
}
public override func value() -> AnyObject? {
return optionValue
}
public override func setDefaultValue(defaultValue: AnyObject) {
if let defaultValue = defaultValue as? Double {
optionValue = defaultValue
}
}
}
| mit |
wordpress-mobile/WordPress-Shared-iOS | WordPressShared/Core/Utility/String+RemovingMatches.swift | 1 | 676 | import Foundation
extension String {
/// Creates a new string by removing all matches of the specified regex.
///
func removingMatches(pattern: String, options: NSRegularExpression.Options = []) -> String {
let range = NSRange(location: 0, length: self.utf16.count)
let regex: NSRegularExpression
do {
regex = try NSRegularExpression(pattern: pattern, options: options)
} catch {
DDLogError(("Error parsing regex: \(error)"))
return self
}
return regex.stringByReplacingMatches(in: self, options: .reportCompletion, range: range, withTemplate: "")
}
}
| gpl-2.0 |
MaddTheSane/MacPaf | Objective C Classes/IndividualEditController.swift | 1 | 8112 | //
// IndividualEditController.swift
// MAF
//
// Created by C.W. Betts on 3/3/15.
//
//
import Cocoa
class IndividualEditController: NSWindowController {
@IBOutlet weak var afn: NSTextField!
@IBOutlet weak var baptismDate: NSTextField!
@IBOutlet weak var baptismTemple: NSComboBox!
@IBOutlet weak var birthForm: NSForm!
@IBOutlet weak var burialForm: NSForm!
@IBOutlet weak var christeningForm: NSForm!
@IBOutlet weak var deathForm: NSForm!
@IBOutlet weak var endowmentDate: NSTextField!
@IBOutlet weak var endowmentTemple: NSComboBox!
@IBOutlet weak var gender: NSPopUpButton!
@IBOutlet weak var givenNames: NSTextField!
@IBOutlet weak var photo: NSImageView!
@IBOutlet weak var rin: NSTextField!
@IBOutlet weak var tabView: NSTabView!
@IBOutlet weak var prefix: NSComboBox!
@IBOutlet weak var suffix: NSComboBox!
@IBOutlet weak var surname: NSComboBox!
@IBOutlet weak var sealingToParentDate: NSTextField!
@IBOutlet weak var sealingToParentTemple: NSComboBox!
@IBOutlet weak var notesIndividualName: NSTextField!
@IBOutlet weak var notesScrollView: NSScrollView!
@IBOutlet weak var attributeTableController: EventTableController!
@IBOutlet weak var eventTableController: EventTableController!
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
@IBAction func cancel(_ sender: AnyObject?) {
}
@IBAction func save(_ sender: AnyObject?) {
}
/*
private Individual individual;
public void windowDidLoad() {
super.windowDidLoad();
log.debug("windowdidload doc=" + document() + " surname=" + surname);
//eventTableController.setup();
attributeTableController.setup();
}
public void cancel(Object sender) { /* IBAction */
// NSApplication.sharedApplication().stopModal();
// NSApplication.sharedApplication().endSheet(window());
// window().orderOut(this);
// NSApplication.sharedApplication().stopModalWithCode(0);
NSApplication.sharedApplication().endSheet(window());
}
public void showWindow(Object o) {
super.showWindow(o);
log.debug("showWindow o=" + o + " surname=" + surname);
}
public void save(Object sender) { /* IBAction */
try {
if (validate()) {
log.debug("IndividualEditController.save() individual b4:" + individual);
MyDocument myDocument = ( (MyDocument) document());
if (individual instanceof Individual.UnknownIndividual) {
individual = myDocument.createAndInsertNewIndividual();
}
individual.setSurname(surname.stringValue());
individual.setGivenNames(givenNames.stringValue());
individual.setNamePrefix(prefix.stringValue());
individual.setNameSuffix(suffix.stringValue());
log.debug("IndividualEditController.save() gendercode:"+gender.titleOfSelectedItem());
log.debug("IndividualEditController.save() gender:"+Gender.genderWithCode(gender.titleOfSelectedItem()));
individual.setGender(Gender.genderWithCode(gender.titleOfSelectedItem()));
individual.setAFN(afn.stringValue());
individual.getBirthEvent().setDateString(birthForm.cellAtIndex(0).stringValue());
individual.getBirthEvent().setPlace(new PlaceJDOM(birthForm.cellAtIndex(1).stringValue()));
individual.getChristeningEvent().setDateString(christeningForm.cellAtIndex(0).stringValue());
individual.getChristeningEvent().setPlace(new PlaceJDOM(christeningForm.cellAtIndex(1).stringValue()));
individual.getDeathEvent().setDateString(deathForm.cellAtIndex(0).stringValue());
individual.getDeathEvent().setPlace(new PlaceJDOM(deathForm.cellAtIndex(1).stringValue()));
individual.getBurialEvent().setDateString(burialForm.cellAtIndex(0).stringValue());
individual.getBurialEvent().setPlace(new PlaceJDOM(burialForm.cellAtIndex(1).stringValue()));
individual.getLDSBaptism().setDateString(baptismDate.stringValue());
individual.getLDSBaptism().setTemple(CocoaUtils.templeForComboBox(baptismTemple));
individual.getLDSEndowment().setDateString(endowmentDate.stringValue());
individual.getLDSEndowment().setTemple(CocoaUtils.templeForComboBox(endowmentTemple));
individual.getLDSSealingToParents().setDateString(sealingToParentDate.stringValue());
individual.getLDSSealingToParents().setTemple(CocoaUtils.templeForComboBox(sealingToParentTemple));
myDocument.setPrimaryIndividual(individual);
log.debug("IndividualEditController.save() individual aft:" + individual);
myDocument.save();
}
}
catch (Exception e) {
// TODO Auto-generated catch block
log.error("Exception: ", e);
}
// NSApplication.sharedApplication().stopModalWithCode(0);
NSApplication.sharedApplication().endSheet(window());
}
/**
* @return
*/
private boolean validate() {
if (StringUtils.isEmpty(""+surname.stringValue()+givenNames.stringValue()+suffix.stringValue())) {
MyDocument.showUserErrorMessage("Please enter at least one name.", "For this Individual to be saved, at least one name (Given, Middle, or Surname) must be entered.");
return false;
}
return true;
}
public void setDocument(NSDocument nsDocument) {
super.setDocument(nsDocument);
log.debug("setdocument:" + nsDocument);
log.debug("surname:" + surname);
Individual primaryIndividual = ( (MyDocument) nsDocument).getPrimaryIndividual();
setIndividual(primaryIndividual);
}
public void setIndividual(Individual newIndividual) {
individual = newIndividual;
surname.setStringValue(individual.getSurname());
surname.selectText(surname);
givenNames.setStringValue(individual.getGivenNames());
prefix.setStringValue(individual.getNamePrefix());
suffix.setStringValue(individual.getNameSuffix());
log.debug("IndividualEdit gender=" + gender.selectedItem().title() + " longstr=" +
individual.getGender().getLongString());
gender.selectItemWithTitle(individual.getGender().getLongString());
birthForm.cellAtIndex(0).setStringValue(individual.getBirthEvent().getDateString());
birthForm.cellAtIndex(1).setStringValue(individual.getBirthEvent().getPlace().getFormatString());
christeningForm.cellAtIndex(0).setStringValue(individual.getChristeningEvent().getDateString());
christeningForm.cellAtIndex(1).setStringValue(individual.getChristeningEvent().getPlace().getFormatString());
deathForm.cellAtIndex(0).setStringValue(individual.getDeathEvent().getDateString());
deathForm.cellAtIndex(1).setStringValue(individual.getDeathEvent().getPlace().getFormatString());
burialForm.cellAtIndex(0).setStringValue(individual.getBurialEvent().getDateString());
burialForm.cellAtIndex(1).setStringValue(individual.getBurialEvent().getPlace().getFormatString());
photo.setImage(MultimediaUtils.makeImageFromMultimedia(individual.getPreferredImage()));
baptismDate.setStringValue(individual.getLDSBaptism().getDateString());
baptismTemple.setStringValue(individual.getLDSBaptism().getTemple().getCode());
endowmentDate.setStringValue(individual.getLDSEndowment().getDateString());
endowmentTemple.setStringValue(individual.getLDSEndowment().getTemple().getCode());
sealingToParentDate.setStringValue(individual.getLDSSealingToParents().getDateString());
sealingToParentTemple.setStringValue(individual.getLDSSealingToParents().getTemple().getCode());
afn.setStringValue(individual.getAFN());
rin.setStringValue(String.valueOf(individual.getRin()));
//eventTableController.setEventSource(newIndividual);
attributeTableController.setEventSource(individual);
attributeTableController.setEventType("attribute");
notesIndividualName.setStringValue(individual.getFullName());
notesTextView.textStorage().setAttributedString(new NSAttributedString(individual.getNoteText()));
tabView.selectFirstTabViewItem(this);
}
// public void openIndividualEditSheet(Object sender) { /* IBAction */
// NSApplication nsapp = NSApplication.sharedApplication();
// nsapp.beginSheet(this.window(), this.window().parentWindow(), null, null, null);
// nsapp.runModalForWindow(this.window());
// nsapp.endSheet(this.window());
// this.window().orderOut(this);
// }
public void windowWillLoad() {
super.windowWillLoad();
log.debug("IEC.windowWillLoad surname=" + surname);
log.debug("IEC.windowwillload doc=" + document());
}
/**
* @return Returns the individual.
*/
public Individual getIndividual() {
return individual;
}
}
*/
}
| bsd-3-clause |
OscarSwanros/swift | validation-test/Reflection/existentials.swift | 16 | 18112 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/existentials
// RUN: %target-run %target-swift-reflection-test %t/existentials | %FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
/*
This file pokes at the swift_reflection_projectExistential API
of the SwiftRemoteMirror library.
It tests the three conditions of existential layout:
- Class existentials
- Existentials whose contained type fits in the 3-word buffer
- Existentials whose contained type has to be allocated into a
raw heap buffer.
- Error existentials, a.k.a. `Error`.
- See also: SwiftReflectionTest.reflect(any:)
- See also: SwiftReflectionTest.reflect(error:)
*/
import SwiftReflectionTest
class MyClass<T, U> {
let x: T
let y: (T, U)
init(x: T, y: (T, U)) {
self.x = x
self.y = y
}
}
struct MyStruct<T, U, V> {
let x: T
let y: U
let z: V
}
protocol MyProtocol {}
protocol MyErrorProtocol : Error {}
struct MyError : MyProtocol, Error {
let i = 0xFEDCBA
}
struct MyCustomError : MyProtocol, MyErrorProtocol {}
struct HasError {
let singleError: Error
let errorInComposition: MyProtocol & Error
let customError: MyErrorProtocol
let customErrorInComposition: MyErrorProtocol & MyProtocol
}
// This will be projected as a class existential, so its
// size doesn't matter.
var mc = MyClass(x: 1010, y: (2020, 3030))
reflect(any: mc)
// CHECK-64: Reflecting an existential.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_class existentials.MyClass
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int))
// CHECK-64: Type info:
// CHECK-64: (reference kind=strong refcounting=native)
// CHECK-32: Reflecting an existential.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_class existentials.MyClass
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int))
// CHECK-32: Type info:
// CHECK-32: (reference kind=strong refcounting=native)
// This value fits in the 3-word buffer in the container.
var smallStruct = MyStruct(x: 1, y: 2, z: 3)
reflect(any: smallStruct)
// CHECK-64: Reflecting an existential.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_struct existentials.MyStruct
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int))
// CHECK-64: Type info:
// CHECK-64: (struct size=24 alignment=8 stride=24 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=x offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=y offset=8
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=z offset=16
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))
// CHECK-32: Reflecting an existential.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_struct existentials.MyStruct
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int))
// CHECK-32: Type info:
// CHECK-32: (struct size=12 alignment=4 stride=12 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=x offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=y offset=4
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=z offset=8
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
// This value will be copied into a heap buffer, with a
// pointer to it in the existential.
var largeStruct = MyStruct(x: (1,1,1), y: (2,2,2), z: (3,3,3))
reflect(any: largeStruct)
// CHECK-64: Reflecting an existential.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_struct existentials.MyStruct
// CHECK-64-NEXT: (tuple
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int))
// CHECK-64-NEXT: (tuple
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int))
// CHECK-64-NEXT: (tuple
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int)))
// CHECK-64: Type info:
// CHECK-64-NEXT: (struct size=72 alignment=8 stride=72 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=x offset=0
// CHECK-64-NEXT: (tuple size=24 alignment=8 stride=24 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=8
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=y offset=24
// CHECK-64-NEXT: (tuple size=24 alignment=8 stride=24 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=8
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=z offset=48
// CHECK-64-NEXT: (tuple size=24 alignment=8 stride=24 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=8
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))))
// CHECK-32: Reflecting an existential.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_struct existentials.MyStruct
// CHECK-32-NEXT: (tuple
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int))
// CHECK-32-NEXT: (tuple
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int))
// CHECK-32-NEXT: (tuple
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int)))
// CHECK-32: Type info:
// CHECK-32: (struct size=36 alignment=4 stride=36 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=x offset=0
// CHECK-32-NEXT: (tuple size=12 alignment=4 stride=12 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=4
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=8
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=y offset=12
// CHECK-32-NEXT: (tuple size=12 alignment=4 stride=12 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=4
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=8
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=z offset=24
// CHECK-32-NEXT: (tuple size=12 alignment=4 stride=12 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=4
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=8
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))))
var he = HasError(singleError: MyError(), errorInComposition: MyError(), customError: MyCustomError(), customErrorInComposition: MyCustomError())
reflect(any: he)
// CHECK-64: Reflecting an existential.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F+]}}
// CHECK-64: Type reference:
// CHECK-64: (struct existentials.HasError)
// CHECK-64: Type info:
// CHECK-64: (struct size=144 alignment=8 stride=144
// CHECK-64-NEXT: (field name=singleError offset=0
// CHECK-64-NEXT: (error_existential size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647
// CHECK-64-NEXT: (field name=error offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))))
// CHECK-64-NEXT: (field name=errorInComposition offset=8
// CHECK-64-NEXT: (opaque_existential size=48 alignment=8 stride=48 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=metadata offset=24
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647))
// CHECK-64-NEXT: (field name=wtable offset=32
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))
// CHECK-64-NEXT: (field name=wtable offset=40
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))
// CHECK-64-NEXT: (field name=customError offset=56
// CHECK-64-NEXT: (opaque_existential size=40 alignment=8 stride=40 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=metadata offset=24
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647))
// CHECK-64-NEXT: (field name=wtable offset=32
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))
// CHECK-64-NEXT: (field name=customErrorInComposition offset=96
// CHECK-64-NEXT: (opaque_existential size=48 alignment=8 stride=48 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=metadata offset=24
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647))
// CHECK-64-NEXT: (field name=wtable offset=32
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))
// CHECK-64-NEXT: (field name=wtable offset=40
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1)))))
// CHECK-32: Reflecting an existential.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (struct existentials.HasError)
// CHECK-32: Type info:
// CHECK-32: (struct size=72 alignment=4 stride=72 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=singleError offset=0
// CHECK-32-NEXT: (error_existential size=4 alignment=4 stride=4 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=error offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))))
// CHECK-32-NEXT: (field name=errorInComposition offset=4
// CHECK-32-NEXT: (opaque_existential size=24 alignment=4 stride=24 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=metadata offset=12
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=wtable offset=16
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))
// CHECK-32-NEXT: (field name=wtable offset=20
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))
// CHECK-32-NEXT: (field name=customError offset=28
// CHECK-32-NEXT: (opaque_existential size=20 alignment=4 stride=20 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=metadata offset=12
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=wtable offset=16
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))
// CHECK-32-NEXT: (field name=customErrorInComposition offset=48
// CHECK-32-NEXT: (opaque_existential size=24 alignment=4 stride=24 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=metadata offset=12
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=wtable offset=16
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))
// CHECK-32-NEXT: (field name=wtable offset=20
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1)))))
reflect(error: MyError())
// CHECK-64: Reflecting an error existential.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (struct existentials.MyError)
// CHECK-64: Type info:
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=i offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))
// CHECK-32: Reflecting an error existential.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (struct existentials.MyError)
// CHECK-32: Type info:
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=i offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
doneReflecting()
| apache-2.0 |
tiagomnh/LicensingViewController | LicensingViewControllerDemo/AppDelegate.swift | 1 | 1636 | //
// AppDelegate.swift
// LicensingViewControllerDemo
//
// Created by Tiago Henriques on 04/08/15.
// Copyright © 2015 Tiago Henriques. All rights reserved.
//
import LicensingViewController
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func applicationDidFinishLaunching(_ application: UIApplication) {
let alamofireItem = LicensingItem(
title: "Alamofire",
license: License.mit(owner: "Alamofire Software Foundation (http://alamofire.org/)", years: "2014")
)
let caniveteItem = LicensingItem(
title: "Canivete",
license: License.mit(owner: "Tiago Henriques (http://tiagomnh.com)", years: "2015")
)
let kingfisherItem = LicensingItem(
title: "Kingfisher",
license: License.mit(owner: "Wei Wang", years: "2015")
)
let nanumfontItem = LicensingItem(
title: "Nanum",
license: License.ofl(owner: "NAVER Corporation (http://www.nhncorp.com)", years: "2010")
)
let licensingViewController = LicensingViewController()
licensingViewController.title = "Acknowledgments"
licensingViewController.items = [alamofireItem, caniveteItem, kingfisherItem, nanumfontItem]
licensingViewController.titleColor = UIButton().tintColor!
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.makeKeyAndVisible()
self.window?.rootViewController = UINavigationController(rootViewController: licensingViewController)
}
}
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/15861-swift-sourcemanager-getmessage.swift | 11 | 224 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
let start = [ {
case
{
enum A {
class
case ,
| mit |
tempestrock/CarPlayer | CarPlayer/Locator.swift | 1 | 8660 | //
// Locator.swift
// Locator
//
// Created by Peter Störmer on 01.12.14.
// Copyright (c) 2014 Tempest Rock Studios. All rights reserved.
//
// KEEP IN MIND: In order for location services to work, add one or both of the following entries to Info.plist by simply adding
// them to the "Information Property List", having type "String" and getting no additional value:
// NSLocationWhenInUseUsageDescription
// NSLocationAlwaysUsageDescription
import Foundation
import CoreLocation
class Locator: CLLocationManager, CLLocationManagerDelegate {
var _locationManager: CLLocationManager!
var _seenError : Bool = false
var _locationStatus : NSString = "Not Started"
// Function to call in the case of new data:
var _notifierFunction : ((Int, String, String, String, String, Double, CLLocationCoordinate2D) -> (Void))?
// Use ',' instead of '." in decimal numbers:
var _useGermanDecimals : Bool
// Location Manager helper stuff
override init() {
_useGermanDecimals = false
super.init()
_seenError = false
_locationManager = CLLocationManager()
_locationManager.delegate = self
// Choose the accuracy according to the battery state of the device:
if (UIDevice.currentDevice().batteryState == UIDeviceBatteryState.Charging) ||
(UIDevice.currentDevice().batteryState == UIDeviceBatteryState.Full) {
// We can spend some more battery. ;)
_locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
} else {
_locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
}
_locationManager.requestAlwaysAuthorization()
_notifierFunction = nil
}
//
// Returns the currently used accuracy (which depends on the battery state).
//
func currentlyUsedAccuracy() -> CLLocationAccuracy {
return _locationManager.desiredAccuracy
}
//
// Sets the notification function that shall be called as soon as new data is available.
//
func setNotifierFunction(funcToCall: (Int, String, String, String, String, Double, CLLocationCoordinate2D) -> Void) {
_notifierFunction = funcToCall
}
//
// Sets the flag whether German decimals (taking a ',' instead of a '.') shall be used and printed out.
//
func setUseGermanDecimals(use: Bool) {
_useGermanDecimals = use
}
//
// Location Manager Delegate stuff
//
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
_locationManager.stopUpdatingLocation()
if !_seenError {
_seenError = true
print(error)
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if _notifierFunction == nil {
return
}
let locationArray: NSArray = locations as NSArray
let locationObj: CLLocation = locationArray.lastObject as! CLLocation
let speed: Double = locationObj.speed // in meters per second
let coord: CLLocationCoordinate2D = locationObj.coordinate
let speedAsInt: Int = (speed > 0 ? Int(speed * 3.6) : Locator.defaultSpeed) // km/h
// Also the string-based variant of the notifier function is about to be called.
let altitude = locationObj.altitude // in meters
let course: Double = locationObj.course
let latString = getNiceLatStringFromCoord(coord.latitude)
let longString = getNiceLongStringFromCoord(coord.longitude)
let altString = (getI18NedDecimalString(altitude.format(".0")) + " m")
let courseString = (course >= 0 ? (getI18NedDecimalString(course.format(".0")) + "°") : defaultCourse())
// Call the notification function that has been provided initially
_notifierFunction!(speedAsInt, latString, longString, altString, courseString, course, coord)
/*
print("Coord: \(latString), \(longString)")
print("Speed: \(speedString)")
print("Altitude: \(altString)")
print("Course: \(courseString)")
*/
}
func getNiceLatStringFromCoord(coord: Double) -> String {
return getNiceStringFromCoord(coord, posChar: "N", negChar: "S")
}
func getNiceLongStringFromCoord(coord: Double) -> String {
return getNiceStringFromCoord(coord, posChar: "E", negChar: "W")
}
//
// Makes something like "053°50,32'N" out of "53.853453"
//
func getNiceStringFromCoord(coord: Double, posChar: Character, negChar: Character) -> String {
// print("Coord: \(coord)")
let separatorChar = (_useGermanDecimals ? "," : ".")
var localCoord = coord
var finalChar: Character
if localCoord < 0 {
finalChar = negChar
localCoord = localCoord * (-1)
} else {
finalChar = posChar
}
var resultStr: String
resultStr = ""
// Get the part of the coordinate that is left of the ".":
let intPartOfCoord = Int(localCoord)
// Make "008" from "8":
resultStr = intPartOfCoord.format("03")
// Remove the integer part from the coordinate
localCoord = localCoord - Double(intPartOfCoord)
// Make the "minutes" part out of the number right of the ".":
localCoord = localCoord * 60
let intPartOfMinutes = Int(localCoord)
resultStr = resultStr + "° " + intPartOfMinutes.format("02") + separatorChar
// Remove the "minutes" part from the coordinate
localCoord = localCoord - Double(intPartOfMinutes)
// Shift three digits further out:
localCoord = localCoord * 10
// Get these two digits alone:
let intPartOfSeconds = Int(localCoord)
resultStr = resultStr + intPartOfSeconds.format("01") + "' "
// Append "N", "S", "E", or "W":
resultStr.append(finalChar)
// print(" --> " + resultStr)
return resultStr
}
//
// Returns a decimal string that has a ',' instead of a '.' if the localization is wanted.
//
func getI18NedDecimalString (str: String) -> String {
if _useGermanDecimals {
let newString = str.stringByReplacingOccurrencesOfString(".", withString: ",", options: NSStringCompareOptions.LiteralSearch, range: nil)
return newString
} else {
return str
}
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
var shouldIAllow = false
switch status {
case CLAuthorizationStatus.Restricted:
_locationStatus = "Restricted Access to location"
case CLAuthorizationStatus.Denied:
_locationStatus = "User denied access to location"
case CLAuthorizationStatus.NotDetermined:
_locationStatus = "Status not determined"
default:
_locationStatus = "Allowed to location Access"
shouldIAllow = true
}
NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
if shouldIAllow {
//DEBUG NSLog("Location to Allowed")
// Start location services
_locationManager.startUpdatingLocation()
// _locationManager.startUpdatingHeading()
} else {
NSLog("Denied access: \(_locationStatus)")
}
}
//
// Returns a default string for an "empty" speed.
//
class var defaultSpeedString: String {
get {
return "--"
}
}
//
// Returns a default value for an "empty" speed.
//
class var defaultSpeed: Int {
get {
return -1
}
}
//
// Returns a default string for an "empty" latitude.
//
func defaultLatitude() -> String {
return "---° --" + (_useGermanDecimals ? "," : ".") + "-' N"
}
//
// Returns a default string for an "empty" longitude.
//
func defaultLongitude() -> String {
return "---° --" + (_useGermanDecimals ? "," : ".") + "-' E"
}
//
// Returns a default string for an "empty" altitude.
//
func defaultAltitude() -> String {
return "-- m"
}
//
// Returns a default string for an "empty" course.
//
func defaultCourse() -> String {
return "---°"
}
}
| gpl-3.0 |
douShu/weiboInSwift | weiboInSwift/weiboInSwift/Classes/Module/Home(首页)/StatusCell/TopView.swift | 1 | 3693 | //
// TopView.swift
// weiboInSwift
//
// Created by 逗叔 on 15/9/11.
// Copyright © 2015年 逗叔. All rights reserved.
//
import UIKit
class TopView: UIView {
// MARK: - |----------------------------- 属性 -----------------------------|
var status: Status? {
didSet {
if let url = status?.user?.imageURL {
iconView.sd_setImageWithURL(url)
}
nameLabel.text = status?.user?.name ?? ""
vipIconView.image = status?.user?.vipImage
memberIconView.image = status?.user?.memberImage
// TODO: 后面会讲
timeLabel.text = NSDate.sinaDate((status?.created_at)!)?.dateDesctiption
sourceLabel.text = status?.source
}
}
override func layoutSubviews() {
super.layoutSubviews()
}
// MARK: - |----------------------------- 构造方法 -----------------------------|
override init(frame: CGRect) {
super.init(frame: frame)
setupSubview()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - |----------------------------- 设置子控件 -----------------------------|
private func setupSubview() {
addSubview(sepView)
addSubview(iconView)
addSubview(nameLabel)
addSubview(timeLabel)
addSubview(sourceLabel)
addSubview(memberIconView)
addSubview(vipIconView)
// 设置布局
sepView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: self, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 10))
iconView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: sepView, size: CGSize(width: 35, height: 35), offset: CGPoint(x: cellSubviewMargin, y: cellSubviewMargin))
nameLabel.ff_AlignHorizontal(type: ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: cellSubviewMargin, y: 0))
timeLabel.ff_AlignHorizontal(type: ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: cellSubviewMargin, y: 0))
sourceLabel.ff_AlignHorizontal(type: ff_AlignType.BottomRight, referView: timeLabel, size: nil, offset: CGPoint(x: cellSubviewMargin, y: 0))
memberIconView.ff_AlignHorizontal(type: ff_AlignType.TopRight, referView: nameLabel, size: nil, offset: CGPoint(x: cellSubviewMargin, y: 0))
vipIconView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: cellSubviewMargin, y: cellSubviewMargin))
}
// MARK: - |----------------------------- 懒加载子控件 -----------------------------|
// 灰色分隔
private lazy var sepView: UIView = {
let v = UIView()
v.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
return v
}()
// 头像
private lazy var iconView: UIImageView = UIImageView()
// 姓名
private lazy var nameLabel: UILabel = UILabel(textLabelColor: UIColor.darkGrayColor(), fontSize: 14)
// 时间标签
private lazy var timeLabel: UILabel = UILabel(textLabelColor: UIColor.orangeColor(), fontSize: 9)
// 来源标签
private lazy var sourceLabel: UILabel = UILabel(textLabelColor: UIColor.lightGrayColor(), fontSize: 9)
// 会员图标
private lazy var memberIconView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
// vip图标
private lazy var vipIconView: UIImageView = UIImageView(image: UIImage(named: "avatar_vip"))
}
| mit |
richardxyx/BoardBank | MonoBank/TokenCollectionViewCell.swift | 1 | 272 | //
// TokenCollectionViewCell.swift
// MonoBank
//
// Created by Richard Neitzke on 04/01/2017.
// Copyright © 2017 Richard Neitzke. All rights reserved.
//
import UIKit
class TokenCollectionViewCell: UICollectionViewCell {
@IBOutlet var tokenView: UIImageView!
}
| mit |
Yalantis/DisplaySwitcher | Example/DisplaySwitcher/Models/User/User.swift | 1 | 644 | //
// User.swift
// YALLayoutTransitioning
//
// Created by Roman on 23.02.16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import UIKit
class User {
var name: String
var surname: String
var avatar: UIImage
var postsCount: Int
var commentsCount: Int
var likesCount: Int
init(name: String, surname: String, avatar: UIImage, postsCount: Int, commentsCount: Int, likesCount: Int) {
self.name = name
self.surname = surname
self.avatar = avatar
self.postsCount = postsCount
self.commentsCount = commentsCount
self.likesCount = likesCount
}
}
| mit |
wantedly/swift-rss-sample | RSSReader/AppDelegate.swift | 3 | 2171 | //
// AppDelegate.swift
// RSSReader
//
// Created by susieyy on 2014/06/03.
// Copyright (c) 2014年 susieyy. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
Coderian/SwiftedGPX | SwiftedGPX/Elements/License.swift | 1 | 1400 | //
// License.swift
// SwiftedGPX
//
// Created by 佐々木 均 on 2016/02/17.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// GPX License
///
/// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd)
///
/// <xsd:element name="license" type="xsd:anyURI" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// Link to external file containing license text.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
public class License : SPXMLElement, HasXMLElementValue, HasXMLElementSimpleValue {
public static var elementName: String = "license"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as Copyright: v.value.license = self
default: break
}
}
}
}
public var value: String!
public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{
self.value = contents
self.parent = parent
return parent
}
public required init(attributes:[String:String]){
super.init(attributes: attributes)
}
} | mit |
vincent-cheny/DailyRecord | DailyRecord/SettingViewController.swift | 1 | 2175 | //
// SettingViewController.swift
// DailyRecord
//
// Created by ChenYong on 16/2/11.
// Copyright © 2016年 LazyPanda. All rights reserved.
//
import UIKit
import Realm
class SettingViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let backItem = UIBarButtonItem()
backItem.title = ""
self.navigationItem.backBarButtonItem = backItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBarHidden = false;
}
@IBAction func resetData(sender: AnyObject) {
let alert = UIAlertController(title: "", message: "确认删除所有记录", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
RecordTemplate().resetTemplate()
Industry().resetIndustry()
Remind().resetRemind()
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(true, forKey: Utils.needBlackCheck)
defaults.setBool(false, forKey: Utils.needWhiteCheck)
defaults.setBool(false, forKey: Utils.needDailySummary)
defaults.setObject([20, 0], forKey: Utils.summaryTime)
defaults.setInteger(4, forKey: Utils.timeSetting1)
defaults.setInteger(8, forKey: Utils.timeSetting2)
defaults.setInteger(10, forKey: Utils.timeSetting3)
defaults.setInteger(13, forKey: Utils.timeSetting4)
defaults.setInteger(17, forKey: Utils.timeSetting5)
defaults.setInteger(21, forKey: Utils.timeSetting6)
}))
alert.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
} | gpl-2.0 |
MenloHacks/ios-app | Menlo Hacks/Pods/Parchment/Parchment/Classes/PagingInvalidationContext.swift | 1 | 134 | import UIKit
open class PagingInvalidationContext: UICollectionViewLayoutInvalidationContext {
var invalidateSizes: Bool = false
}
| mit |
KaushalElsewhere/AllHandsOn | SwaggerAPiConnect/SwaggerAPiConnect/AppDelegate.swift | 1 | 2167 | //
// AppDelegate.swift
// SwaggerAPiConnect
//
// Created by Kaushal Elsewhere on 15/11/2016.
// Copyright © 2016 Kaushal Elsewhere. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
PlutoMa/SwiftProjects | 008.Color Gradient/ColorGradient/ColorGradient/ViewController.swift | 1 | 4023 | //
// ViewController.swift
// ColorGradient
//
// Created by Dareway on 2017/10/18.
// Copyright © 2017年 Pluto. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let gradientLayer = CAGradientLayer()
let timeLabel = UILabel()
let temperatureLabel = UILabel()
var colorSets = [[CGColor]]()
var currentTime: Int = 0 {
didSet {
guard currentTime > 0 && currentTime < 24 else {
return
}
timeLabel.text = "\(currentTime):00"
if currentTime > 12 {
temperatureLabel.text = "\(highestTemperature - currentTime)℃"
gradientLayer.colors = colorSets[colorSets.count - 1 - (currentTime - 12)]
} else {
temperatureLabel.text = "\(lowestTemperature + currentTime - 1)℃"
gradientLayer.colors = colorSets[currentTime - 1]
}
}
}
var lastValue: Int = 0
let brightestSkyColor_R = 21.0
let brightestSkyColor_G = 105.0
let brightestSkyColor_B = 203.0
let darkestSkyColor_R = 8.0
let darkestSkyColor_G = 33.0
let darkestSkyColor_B = 63.0
let highestTemperatureColor_R = 255.0
let highestTemperatureColor_G = 200.0
let highestTemperatureColor_B = 101.0
let lowestTemperatureColor_R = 47.0
let lowestTemperatureColor_G = 169.0
let lowestTemperatureColor_B = 199.0
let lowestTemperature = 18
let highestTemperature = 41
override func viewDidLoad() {
super.viewDidLoad()
createColorSets()
gradientLayer.frame = view.bounds
view.layer.addSublayer(gradientLayer)
timeLabel.frame = CGRect(x: 50, y: 40, width: 100, height: 100)
timeLabel.textColor = UIColor.white
timeLabel.font = UIFont.systemFont(ofSize: 28)
view.addSubview(timeLabel)
temperatureLabel.frame = CGRect(x: 250, y: 40, width: 100, height: 100)
temperatureLabel.textColor = UIColor.white
temperatureLabel.font = UIFont.systemFont(ofSize: 28)
view.addSubview(temperatureLabel)
currentTime = 1
lastValue = 1
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handelPanGesture(sender:)))
self.view.addGestureRecognizer(panGestureRecognizer)
}
@objc
func handelPanGesture(sender: UIPanGestureRecognizer) {
let tranY = sender.translation(in: view).y
let space = view.frame.height / 22
let change = Int(tranY / space)
let newValue = lastValue + change
guard newValue > 0 && newValue < 24 else {
return
}
currentTime = newValue
if sender.state == .ended {
lastValue = currentTime
}
}
func createColorSets() -> Void {
for i in 0...12 {
let index = Double(i)
let sky_r = darkestSkyColor_R + (brightestSkyColor_R - darkestSkyColor_R) * (index - 1) / 11.0
let sky_g = darkestSkyColor_G + (brightestSkyColor_G - darkestSkyColor_G) * (index - 1) / 11.0
let sky_b = darkestSkyColor_B + (brightestSkyColor_B - darkestSkyColor_B) * (index - 1) / 11.0
let tmpr_r = lowestTemperatureColor_R + (highestTemperatureColor_R - lowestTemperatureColor_R) * (index - 1) / 11.0
let tmpr_g = lowestTemperatureColor_G + (highestTemperatureColor_G - lowestTemperatureColor_G) * (index - 1) / 11.0
let tmpr_b = lowestTemperatureColor_B + (highestTemperatureColor_B - lowestTemperatureColor_B) * (index - 1) / 11.0
let color = [UIColor(red: CGFloat(sky_r/255.0), green: CGFloat(sky_g/255.0), blue: CGFloat(sky_b/255.0), alpha: 1).cgColor,
UIColor(red: CGFloat(tmpr_r/255.0), green: CGFloat(tmpr_g/255.0), blue: CGFloat(tmpr_b/255.0), alpha: 1).cgColor]
colorSets.append(color)
}
}
}
| mit |
ahoppen/swift | test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1distinct_generic_use.swift | 14 | 3533 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5OuterOyAA5InnerVySiGGWV" = linkonce_odr hidden constant %swift.enum_vwtable
// CHECK: @"$s4main5OuterOyAA5InnerVySiGGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// CHECK-SAME: i8** getelementptr inbounds (
// CHECK-SAME: %swift.enum_vwtable,
// CHECK-SAME: %swift.enum_vwtable* @"$s4main5OuterOyAA5InnerVySiGGWV",
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 0
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5OuterOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: {{(\[4 x i8\],)?}}
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5InnerVySiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
enum Outer<First> {
case first(First)
}
struct Inner<First> {
let first: First
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5OuterOyAA5InnerVySiGGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Outer.first(Inner(first: 13)) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5OuterOMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_TYPE]],
// CHECK-SAME: i8* undef,
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5OuterOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 |
ahoppen/swift | SwiftCompilerSources/Sources/SIL/Location.swift | 2 | 598 | //===--- Location.swift - Source location ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SILBridging
public struct Location {
let bridged: BridgedLocation
}
| apache-2.0 |
ahoppen/swift | test/Interpreter/SDK/objc_cast.swift | 13 | 19063 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
@objc protocol SwiftObjCProto {}
class SwiftSuperPort : Port { }
class SwiftSubPort : SwiftSuperPort { }
class SwiftSuper { }
class SwiftSub : SwiftSuper { }
extension Port : SwiftObjCProto {}
var obj : AnyObject
func genericCast<T>(_ x: AnyObject, _: T.Type) -> T? {
return x as? T
}
func genericCastObjCBound<T: NSObject>(_ x: AnyObject, _: T.Type) -> T? {
return x as? T
}
// Test instance of Swift subclass of Objective-C class
obj = SwiftSubPort()
_ = obj as! SwiftSubPort
_ = obj as! SwiftSuperPort
_ = (obj as? Port)
_ = (obj as? NSObject)!
if (obj as? SwiftSubPort) == nil { abort() }
if (obj as? SwiftSuperPort) == nil { abort() }
if (obj as? Port) == nil { abort() }
if (obj as? NSObject) == nil { abort() }
if (obj as? NSArray) != nil { abort() }
if (obj as? SwiftSub) != nil { abort() }
if (obj as? SwiftSuper) != nil { abort() }
obj = SwiftSuperPort()
_ = obj as! SwiftSuperPort
_ = obj as! Port
_ = obj as! NSObject
if (obj as? SwiftSubPort) != nil { abort() }
if (obj as? SwiftSuperPort) == nil { abort() }
if (obj as? Port) == nil { abort() }
if (obj as? NSObject) == nil { abort() }
if (obj as? NSArray) != nil { abort() }
if (obj as? SwiftSub) != nil { abort() }
if (obj as? SwiftSuper) != nil { abort() }
// Test instance of Objective-C class that has Swift subclass
obj = Port()
_ = obj as! Port
_ = obj as! NSObject
if (obj as? SwiftSubPort) != nil { abort() }
if (obj as? SwiftSuperPort) != nil { abort() }
if (obj as? Port) == nil { abort() }
if (obj as? NSObject) == nil { abort() }
if (obj as? NSArray) != nil { abort() }
if (obj as? SwiftSub) != nil { abort() }
if (obj as? SwiftSuper) != nil { abort() }
if (obj as? SwiftObjCProto) == nil { abort() }
obj = Port()
_ = genericCast(obj, Port.self)!
_ = genericCast(obj, NSObject.self)!
if genericCast(obj, SwiftSubPort.self) != nil { abort() }
if genericCast(obj, SwiftSuperPort.self) != nil { abort() }
if genericCast(obj, Port.self) == nil { abort() }
if genericCast(obj, NSObject.self) == nil { abort() }
if genericCast(obj, NSArray.self) != nil { abort() }
if genericCast(obj, SwiftSub.self) != nil { abort() }
if genericCast(obj, SwiftSuper.self) != nil { abort() }
_ = genericCastObjCBound(obj, Port.self)!
_ = genericCastObjCBound(obj, NSObject.self)!
if genericCastObjCBound(obj, SwiftSubPort.self) != nil { abort() }
if genericCastObjCBound(obj, SwiftSuperPort.self) != nil { abort() }
if genericCastObjCBound(obj, Port.self) == nil { abort() }
if genericCastObjCBound(obj, NSObject.self) == nil { abort() }
if genericCastObjCBound(obj, NSArray.self) != nil { abort() }
obj = NSObject()
_ = obj as! NSObject
if (obj as? SwiftSubPort) != nil { abort() }
if (obj as? SwiftSuperPort) != nil { abort() }
if (obj as? Port) != nil { abort() }
if (obj as? NSObject) == nil { abort() }
if (obj as? NSCopying) != nil { abort() }
if (obj as? NSArray) != nil { abort() }
if (obj as? SwiftSub) != nil { abort() }
if (obj as? SwiftSuper) != nil { abort() }
if (obj as? SwiftObjCProto) != nil { abort() }
// Test instance of a tagged pointer type
obj = NSNumber(value: 1234567)
_ = obj as! NSNumber
_ = obj as! NSValue
_ = obj as! NSObject
_ = obj as! NSCopying
if (obj as? SwiftSubPort) != nil { abort() }
if (obj as? SwiftSuperPort) != nil { abort() }
if (obj as? NSNumber) == nil { abort() }
if (obj as? NSValue) == nil { abort() }
if (obj as? NSObject) == nil { abort() }
if (obj as? NSCopying) == nil { abort() }
if (obj as? NSArray) != nil { abort() }
if (obj as? SwiftSub) != nil { abort() }
if (obj as? SwiftSuper) != nil { abort() }
// Test instance of a Swift class with no Objective-C inheritance
obj = SwiftSub()
_ = obj as! SwiftSub
_ = obj as! SwiftSuper
if (obj as? SwiftSubPort) != nil { abort() }
if (obj as? SwiftSuperPort) != nil { abort() }
if (obj as? NSObject) != nil { abort() }
if (obj as? NSArray) != nil { abort() }
if (obj as? SwiftSub) == nil { abort() }
if (obj as? SwiftSuper) == nil { abort() }
obj = SwiftSuper()
_ = obj as! SwiftSuper
if (obj as? SwiftSubPort) != nil { abort() }
if (obj as? SwiftSuperPort) != nil { abort() }
if (obj as? NSObject) != nil { abort() }
if (obj as? NSArray) != nil { abort() }
if (obj as? SwiftSub) != nil { abort() }
if (obj as? SwiftSuper) == nil { abort() }
// Test optional and non-optional bridged conversions
var ao: AnyObject = "s" as NSObject
ao as! String
ao is String
var auo: AnyObject! = "s" as NSObject
var s: String = auo as! String
var auoo: AnyObject? = "s" as NSObject
auoo! as? String
// Test bridged casts.
// CHECK: Downcast to hello
obj = NSString(string: "hello")
if let str = obj as? String {
print("Downcast to \(str)")
} else {
print("Not a string?")
}
// Forced cast using context
// CHECK-NEXT: Forced to string hello
let forcedStr: String = obj as! String
print("Forced to string \(forcedStr)")
// CHECK-NEXT: Downcast to Swift
var objOpt: AnyObject? = NSString(string: "Swift")
if let str = objOpt as? String {
print("Downcast to \(str)")
} else {
print("Not a string?")
}
// Forced cast using context
// CHECK-NEXT: Forced to string Swift
let forcedStrOpt: String = objOpt as! String
print("Forced to string \(forcedStrOpt)")
// CHECK-NEXT: Downcast to world
var objImplicitOpt: AnyObject! = NSString(string: "world")
if let str = objImplicitOpt as? String {
print("Downcast to \(str)")
} else {
print("Not a string?")
}
// Forced cast using context
// CHECK-NEXT: Forced to string world
let forcedStrImplicitOpt: String = objImplicitOpt as! String
print("Forced to string \(forcedStrImplicitOpt)")
// CHECK-NEXT: Downcast correctly failed due to nil
objOpt = nil
if let str = objOpt as? String {
print("Downcast should not succeed for nil")
} else {
print("Downcast correctly failed due to nil")
}
// CHECK-NEXT: Downcast correctly failed due to nil
objImplicitOpt = nil
if let str = objImplicitOpt as? String {
print("Downcast should not succeed for nil")
} else {
print("Downcast correctly failed due to nil")
}
// Test bridged "isa" checks.
// CHECK: It's a string!
obj = NSString(string: "hello")
if obj is String {
print("It's a string!")
} else {
print("Not a string?")
}
// CHECK-NEXT: It's a string!
objOpt = NSString(string: "Swift")
if objOpt is String {
print("It's a string!")
} else {
print("Not a string?")
}
// CHECK-NEXT: It's a string!
objImplicitOpt = NSString(string: "world")
if objImplicitOpt is String {
print("It's a string!")
} else {
print("Not a string?")
}
// CHECK-NEXT: Isa correctly failed due to nil
objOpt = nil
if objOpt is String {
print("Isa should not succeed for nil")
} else {
print("Isa correctly failed due to nil")
}
// CHECK-NEXT: Isa correctly failed due to nil
objImplicitOpt = nil
if objImplicitOpt is String {
print("Isa should not succeed for nil")
} else {
print("Isa correctly failed due to nil")
}
let words = ["Hello", "Swift", "World"]
// CHECK-NEXT: Object-to-bridged-array cast produced ["Hello", "Swift", "World"]
obj = words as AnyObject
if let strArr = obj as? [String] {
print("Object-to-bridged-array cast produced \(strArr)")
} else {
print("Object-to-bridged-array cast failed")
}
// Check downcast from the bridged type itself.
// CHECK-NEXT: NSArray-to-bridged-array cast produced ["Hello", "Swift", "World"]
var nsarr = words as NSArray
if let strArr = nsarr as? [String] {
print("NSArray-to-bridged-array cast produced \(strArr)")
} else {
print("NSArray-to-bridged-array cast failed")
}
// CHECK-NEXT: NSArray?-to-bridged-array cast produced ["Hello", "Swift", "World"]
var nsarrOpt = words as NSArray?
if let strArr = nsarrOpt as? [String] {
print("NSArray?-to-bridged-array cast produced \(strArr)")
} else {
print("NSArray?-to-bridged-array cast failed")
}
// CHECK-NEXT: NSArray!-to-bridged-array cast produced ["Hello", "Swift", "World"]
var nsarrImplicitOpt = words as NSArray!
if let strArr = nsarrImplicitOpt as? [String] {
print("NSArray!-to-bridged-array cast produced \(strArr)")
} else {
print("NSArray!-to-bridged-array cast failed")
}
// Check downcast from a superclass of the bridged type.
// CHECK-NEXT: NSObject-to-bridged-array cast produced ["Hello", "Swift", "World"]
var nsobj: NSObject = nsarr
if let strArr = nsobj as? [String] {
print("NSObject-to-bridged-array cast produced \(strArr)")
} else {
print("NSObject-to-bridged-array cast failed")
}
// CHECK-NEXT: NSArray is [String]
if nsarr is [String] {
print("NSArray is [String]")
} else {
print("NSArray is not a [String]")
}
// CHECK-NEXT: NSArray? is [String]
if nsarrOpt is [String] {
print("NSArray? is [String]")
} else {
print("NSArray? is not a [String]")
}
// CHECK-NEXT: NSArray! is [String]
if nsarrImplicitOpt is [String] {
print("NSArray! is [String]")
} else {
print("NSArray! is not a [String]")
}
// CHECK-NEXT: NSObject is [String]
if nsobj is [String] {
print("NSObject is [String]")
} else {
print("NSObject is not a [String]")
}
// Forced downcast based on context.
// CHECK-NEXT: Forced to string array ["Hello", "Swift", "World"]
var forcedStrArray: [String] = obj as! [String]
print("Forced to string array \(forcedStrArray)")
// CHECK-NEXT: Forced NSArray to string array ["Hello", "Swift", "World"]
forcedStrArray = nsarr as! [String]
print("Forced NSArray to string array \(forcedStrArray)")
// CHECK-NEXT: Forced NSArray? to string array ["Hello", "Swift", "World"]
forcedStrArray = nsarrOpt as! [String]
print("Forced NSArray? to string array \(forcedStrArray)")
// CHECK-NEXT: Forced NSArray! to string array ["Hello", "Swift", "World"]
forcedStrArray = nsarrImplicitOpt as! [String]
print("Forced NSArray! to string array \(forcedStrArray)")
// CHECK-NEXT: Object-to-array cast produced [Hello, Swift, World]
if let strArr = obj as? [NSString] {
print("Object-to-array cast produced \(strArr)")
} else {
print("Object-to-array cast failed")
}
// CHECK-NEXT: Object-to-bridged-array cast failed due to bridge mismatch
if let strArr = obj as? [Int] {
print("Object-to-bridged-array cast should not have succeeded")
} else {
print("Object-to-bridged-array cast failed due to bridge mismatch")
}
// CHECK-NEXT: Array of strings is not an array of ints
if obj is [Int] {
print("Array of strings should not be an array of ints!")
} else {
print("Array of strings is not an array of ints")
}
// Implicitly unwrapped optional of object to array casts.
// CHECK-NEXT: Object-to-bridged-array cast produced ["Hello", "Swift", "World"]
objOpt = words as AnyObject?
if let strArr = objOpt as? [String] {
print("Object-to-bridged-array cast produced \(strArr)")
} else {
print("Object-to-bridged-array cast failed")
}
// Forced downcast based on context.
// CHECK-NEXT: Forced to string array ["Hello", "Swift", "World"]
let forcedStrArrayOpt: [String] = objOpt as! [String]
print("Forced to string array \(forcedStrArrayOpt)")
// CHECK-NEXT: Object-to-array cast produced [Hello, Swift, World]
if let strArr = objOpt as? [NSString] {
print("Object-to-array cast produced \(strArr)")
} else {
print("Object-to-array cast failed")
}
// CHECK: Object-to-bridged-array cast failed due to bridge mismatch
if let intArr = objOpt as? [Int] {
print("Object-to-bridged-array cast should not have succeeded")
} else {
print("Object-to-bridged-array cast failed due to bridge mismatch")
}
// CHECK: Object-to-bridged-array cast failed due to nil
objOpt = nil
if let strArr = objOpt as? [String] {
print("Cast from nil succeeded?")
} else {
print("Object-to-bridged-array cast failed due to nil")
}
// Optional of object to array casts.
// CHECK-NEXT: Object-to-bridged-array cast produced ["Hello", "Swift", "World"]
objImplicitOpt = words as AnyObject!
if let strArr = objImplicitOpt as? [String] {
print("Object-to-bridged-array cast produced \(strArr)")
} else {
print("Object-to-bridged-array cast failed")
}
// Forced downcast based on context.
// CHECK-NEXT: Forced to string array ["Hello", "Swift", "World"]
let forcedStrArrayImplicitOpt: [String] = objImplicitOpt as! [String]
print("Forced to string array \(forcedStrArrayImplicitOpt)")
// CHECK-NEXT: Object-to-array cast produced [Hello, Swift, World]
if let strArr = objImplicitOpt as? [NSString] {
print("Object-to-array cast produced \(strArr)")
} else {
print("Object-to-array cast failed")
}
// CHECK: Object-to-bridged-array cast failed due to bridge mismatch
if let intArr = objImplicitOpt as? [Int] {
print("Object-to-bridged-array cast should not have succeeded")
} else {
print("Object-to-bridged-array cast failed due to bridge mismatch")
}
// CHECK: Object-to-bridged-array cast failed due to nil
objImplicitOpt = nil
if let strArr = objImplicitOpt as? [String] {
print("Cast from nil succeeded?")
} else {
print("Object-to-bridged-array cast failed due to nil")
}
// Casting an array of numbers to different numbers.
// CHECK: Numbers-as-doubles cast produces [3.9375, 2.71828, 0.0]
obj = ([3.9375, 2.71828, 0] as [Double]) as AnyObject
if let doubleArr = obj as? [Double] {
print(MemoryLayout<Double>.size)
print("Numbers-as-doubles cast produces \(doubleArr)")
} else {
print("Numbers-as-doubles failed")
}
// CHECK-FAIL: Numbers-as-floats cast produces [3.9375, 2.71828{{.*}}, 0.0]
// TODO: check if this is intention: rdar://33021520
if let floatArr = obj as? [Float] {
print(MemoryLayout<Float>.size)
print("Numbers-as-floats cast produces \(floatArr)")
} else {
print("Numbers-as-floats failed")
}
// CHECK-FAIL: Numbers-as-ints cast produces [3, 2, 0]
// TODO: check if this is intention: rdar://33021520
if let intArr = obj as? [Int] {
print("Numbers-as-ints cast produces \(intArr)")
} else {
print("Numbers-as-ints failed")
}
// CHECK-FAIL: Numbers-as-bools cast produces [true, true, false]
// TODO: check if this is intention: rdar://33021520
if let boolArr = obj as? [Bool] {
print("Numbers-as-bools cast produces \(boolArr)")
} else {
print("Numbers-as-bools failed")
}
class Base : NSObject {
override var description: String {
return "Base"
}
}
class Derived : Base {
override var description: String {
return "Derived"
}
}
// CHECK: Array-of-base cast produces [Derived, Derived, Base]
obj = [Derived(), Derived(), Base()] as NSObject
if let baseArr = obj as? [Base] {
print("Array-of-base cast produces \(baseArr)")
} else {
print("Not an array of base")
}
// CHECK: Not an array of derived
if let derivedArr = obj as? [Derived] {
print("Array-of-derived cast produces \(derivedArr)")
} else {
print("Not an array of derived")
}
// CHECK: Dictionary-of-base-base cast produces
obj = [Derived() : Derived(), Derived() : Base(), Derived() : Derived() ] as AnyObject
if let baseDict = obj as? Dictionary<Base, Base> {
print("Dictionary-of-base-base cast produces \(baseDict)")
} else {
print("Not a dictionary of base/base")
}
// CHECK: Dictionary-of-derived-base cast produces
if let baseDict = obj as? Dictionary<Derived, Base> {
print("Dictionary-of-derived-base cast produces \(baseDict)")
} else {
print("Not a dictionary of derived/base")
}
// CHECK: Not a dictionary of derived/derived
if let dict = obj as? Dictionary<Derived, Derived> {
print("Dictionary-of-derived-derived cast produces \(dict)")
} else {
print("Not a dictionary of derived/derived")
}
let strArray: AnyObject = ["hello", "world"] as NSObject
let intArray: AnyObject = [1, 2, 3] as NSObject
let dictArray: AnyObject = [["hello" : 1, "world" : 2],
["swift" : 1, "speedy" : 2]] as NSObject
// CHECK: Dictionary<String, AnyObject> is
obj = ["a" : strArray, "b" : intArray, "c": dictArray] as NSObject
if let dict = obj as? Dictionary<String, [AnyObject]> {
print("Dictionary<String, AnyObject> is \(dict)")
} else {
print("Not a Dictionary<String, AnyObject>")
}
// CHECK: Not a Dictionary<String, String>
if let dict = obj as? Dictionary<String, [String]> {
print("Dictionary<String, String> is \(dict)")
} else {
print("Not a Dictionary<String, String>")
}
// CHECK: Not a Dictionary<String, Int>
if let dict = obj as? Dictionary<String, [Int]> {
print("Dictionary<String, Int> is \(dict)")
} else {
print("Not a Dictionary<String, Int>")
}
// CHECK: [Dictionary<String, Int>] is
obj = dictArray
if let array = obj as? [Dictionary<String, Int>] {
print("[Dictionary<String, Int>] is \(array)")
} else {
print("Not a [Dictionary<String, Int>]")
}
// CHECK: Not a [Dictionary<String, String>]
if let array = obj as? [Dictionary<String, String>] {
print("[Dictionary<String, String>] is \(array)")
} else {
print("Not a [Dictionary<String, String>]")
}
// CHECK: Dictionary<String, [Dictionary<String, Int>]> is ["a": [
obj = ["a" : dictArray] as NSObject
if let dict = obj as? Dictionary<String, [Dictionary<String, Int>]> {
print("Dictionary<String, [Dictionary<String, Int>]> is \(dict)")
} else {
print("Not a Dictionary<String, [Dictionary<String, Int>]>")
}
// CHECK: Not a Dictionary<String, [Dictionary<String, String>]>
if let dict = obj as? Dictionary<String, [Dictionary<String, String>]> {
print("Dictionary<String, [Dictionary<String, String>]> is \(dict)")
} else {
print("Not a Dictionary<String, [Dictionary<String, String>]>")
}
// CHECK: [Dictionary<String, [Dictionary<String, Int>]>] is
obj = [obj, obj, obj] as NSObject
if let array = obj as? [Dictionary<String, [Dictionary<String, Int>]>] {
print("[Dictionary<String, [Dictionary<String, Int>]>] is \(array)")
} else {
print("Not a [Dictionary<String, [Dictionary<String, Int>]>]")
}
// CHECK: Not a Dictionary<String, [Dictionary<String, String>]>[]
if let array = obj as? Dictionary<String, [Dictionary<String, String>]> {
print("Dictionary<String, [Dictionary<String, String>]>[] is \(array)")
} else {
print("Not a Dictionary<String, [Dictionary<String, String>]>[]")
}
// Helper function that downcasts
func downcastToStringArrayOptOpt(_ obj: AnyObject???!) {
if let strArrOptOpt = obj as? [String]?? {
if let strArrOpt = strArrOptOpt {
if let strArr = strArrOpt {
print("some(some(some(\(strArr))))")
} else {
print("some(some(none))")
}
} else {
print("some(none)")
}
} else {
print("none")
}
}
// CHECK: {{^}}some(some(some(["a", "b", "c"]))){{$}}
var objOptOpt: AnyObject?? = .some(.some(["a", "b", "c"] as NSObject))
downcastToStringArrayOptOpt(objOptOpt)
// CHECK: {{^}}none{{$}}
objOptOpt = .some(.some([1 : "hello", 2 : "swift", 3 : "world"] as NSObject))
downcastToStringArrayOptOpt(objOptOpt)
// CHECK: {{^}}none{{$}}
objOptOpt = .some(.some([1, 2, 3] as NSObject))
downcastToStringArrayOptOpt(objOptOpt)
print("ok") // CHECK: ok
| apache-2.0 |
dreamsxin/swift | test/SILGen/objc_imported_generic.swift | 1 | 5187 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen %s | FileCheck %s
// For integration testing, ensure we get through IRGen too.
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-ir -verify -DIRGEN_INTEGRATION_TEST %s
// REQUIRES: objc_interop
import objc_generics
func callInitializer() {
_ = GenericClass(thing: NSObject())
}
// CHECK-LABEL: sil shared @_TFCSo12GenericClassCfT5thingGSQx__GSQGS_x__
// CHECK: thick_to_objc_metatype {{%.*}} : $@thick GenericClass<T>.Type to $@objc_metatype GenericClass<T>.Type
public func genericMethodOnAnyObject(o: AnyObject, b: Bool) -> AnyObject {
return o.thing!()!
}
// CHECK-LABEL: sil @_TF21objc_imported_generic24genericMethodOnAnyObject
// CHECK: dynamic_method [volatile] {{%.*}} : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!1.foreign : <T where T : AnyObject> GenericClass<T> -> () -> T?, $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>
public func genericMethodOnAnyObjectChained(o: AnyObject, b: Bool) -> AnyObject? {
return o.thing?()
}
// CHECK-LABEL: sil @_TF21objc_imported_generic31genericMethodOnAnyObjectChained
// CHECK: dynamic_method_br %4 : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!1.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
public func genericSubscriptOnAnyObject(o: AnyObject, b: Bool) -> AnyObject? {
return o[0 as UInt16]
}
// CHECK-LABEL: sil @_TF21objc_imported_generic27genericSubscriptOnAnyObject
// CHECK: dynamic_method_br %4 : $@opened([[TAG:.*]]) AnyObject, #GenericClass.subscript!getter.1.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) @pseudogeneric (UInt16, @opened([[TAG]]) AnyObject) -> @autoreleased AnyObject):
public func genericPropertyOnAnyObject(o: AnyObject, b: Bool) -> AnyObject?? {
return o.propertyThing
}
// CHECK-LABEL: sil @_TF21objc_imported_generic26genericPropertyOnAnyObject
// CHECK: dynamic_method_br %4 : $@opened([[TAG:.*]]) AnyObject, #GenericClass.propertyThing!getter.1.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
protocol ThingHolder {
associatedtype Thing
init!(thing: Thing!)
func thing() -> Thing?
func arrayOfThings() -> [Thing]
func setArrayOfThings(_: [Thing])
static func classThing() -> Thing?
var propertyThing: Thing? { get set }
var propertyArrayOfThings: [Thing]? { get set }
}
// TODO: Crashes in IRGen because the type metadata for `T` is not found in
// the witness thunk to satisfy the associated type requirement. This could be
// addressed by teaching IRGen to fulfill erased type parameters from protocol
// witness tables (rdar://problem/26602097).
#if !IRGEN_INTEGRATION_TEST
extension GenericClass: ThingHolder {}
#endif
public func genericBlockBridging<T: AnyObject>(x: GenericClass<T>) {
let block = x.blockForPerformingOnThings()
x.performBlock(onThings: block)
}
// CHECK-LABEL: sil @_TF21objc_imported_generic20genericBlockBridging
// CHECK: [[BLOCK_TO_FUNC:%.*]] = function_ref @_TTRGRxs9AnyObjectrXFdCb_dx_ax_XFo_ox_ox_
// CHECK: partial_apply [[BLOCK_TO_FUNC]]<T>
// CHECK: [[FUNC_TO_BLOCK:%.*]] = function_ref @_TTRGRxs9AnyObjectrXFo_ox_ox_XFdCb_dx_ax_
// CHECK: init_block_storage_header {{.*}} invoke [[FUNC_TO_BLOCK]]<T>
// CHECK-LABEL: sil @_TF21objc_imported_generic20arraysOfGenericParam
public func arraysOfGenericParam<T: AnyObject>(y: Array<T>) {
// CHECK: function_ref {{@_TFCSo12GenericClassCfT13arrayOfThings.*}} : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@owned Array<τ_0_0>, @thick GenericClass<τ_0_0>.Type) -> @owned ImplicitlyUnwrappedOptional<GenericClass<τ_0_0>>
let x = GenericClass<T>(arrayOfThings: y)!
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.setArrayOfThings!1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, GenericClass<τ_0_0>) -> ()
x.setArrayOfThings(y)
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!getter.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (GenericClass<τ_0_0>) -> @autoreleased Optional<NSArray>
_ = x.propertyArrayOfThings
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!setter.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (Optional<NSArray>, GenericClass<τ_0_0>) -> ()
x.propertyArrayOfThings = y
}
// CHECK-LABEL: sil shared [thunk] @_TTOFCSo12GenericClasscfT13arrayOfThings
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.init!initializer.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, @owned GenericClass<τ_0_0>) -> @owned ImplicitlyUnwrappedOptional<GenericClass<τ_0_0>>
| apache-2.0 |
dst-hackathon/socialradar-ios | SocialRadar/SocialRadar/AppDelegate.swift | 1 | 2144 | //
// AppDelegate.swift
// SocialRadar
//
// Created by Thawee on 10/31/14.
// Copyright (c) 2014 dsthackathon. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
Zewo/PostgreSQL | Sources/PostgreSQL/FieldInfo.swift | 2 | 224 | @_exported import SQL
public struct FieldInfo: SQL.FieldInfoProtocol {
public let name: String
public let index: Int
init(name: String, index: Int) {
self.name = name
self.index = index
}
}
| mit |
e78l/swift-corelibs-foundation | Foundation/URLRequest.swift | 1 | 11767 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftFoundation
#else
import Foundation
#endif
public struct URLRequest : ReferenceConvertible, Equatable, Hashable {
public typealias ReferenceType = NSURLRequest
public typealias CachePolicy = NSURLRequest.CachePolicy
public typealias NetworkServiceType = NSURLRequest.NetworkServiceType
/*
NSURLRequest has a fragile ivar layout that prevents the swift subclass approach here, so instead we keep an always mutable copy
*/
internal var _handle: _MutableHandle<NSMutableURLRequest>
internal mutating func _applyMutation<ReturnType>(_ whatToDo : (NSMutableURLRequest) -> ReturnType) -> ReturnType {
if !isKnownUniquelyReferenced(&_handle) {
let ref = _handle._uncopiedReference()
_handle = _MutableHandle(reference: ref)
}
return whatToDo(_handle._uncopiedReference())
}
/// Creates and initializes a URLRequest with the given URL and cache policy.
/// - parameter url: The URL for the request.
/// - parameter cachePolicy: The cache policy for the request. Defaults to `.useProtocolCachePolicy`
/// - parameter timeoutInterval: The timeout interval for the request. See the commentary for the `timeoutInterval` for more information on timeout intervals. Defaults to 60.0
public init(url: URL, cachePolicy: CachePolicy = .useProtocolCachePolicy, timeoutInterval: TimeInterval = 60.0) {
_handle = _MutableHandle(adoptingReference: NSMutableURLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval))
}
fileprivate init(_bridged request: NSURLRequest) {
_handle = _MutableHandle(reference: request.mutableCopy() as! NSMutableURLRequest)
}
/// The URL of the receiver.
public var url: URL? {
get {
return _handle.map { $0.url }
}
set {
_applyMutation { $0.url = newValue }
}
}
/// The cache policy of the receiver.
public var cachePolicy: CachePolicy {
get {
return _handle.map { $0.cachePolicy }
}
set {
_applyMutation { $0.cachePolicy = newValue }
}
}
//URLRequest.timeoutInterval should be given precedence over the URLSessionConfiguration.timeoutIntervalForRequest regardless of the value set,
// if it has been set at least once. Even though the default value is 60 ,if the user sets URLRequest.timeoutInterval
// to explicitly 60 then the precedence should be given to URLRequest.timeoutInterval.
internal var isTimeoutIntervalSet = false
/// Returns the timeout interval of the receiver.
/// - discussion: The timeout interval specifies the limit on the idle
/// interval allotted to a request in the process of loading. The "idle
/// interval" is defined as the period of time that has passed since the
/// last instance of load activity occurred for a request that is in the
/// process of loading. Hence, when an instance of load activity occurs
/// (e.g. bytes are received from the network for a request), the idle
/// interval for a request is reset to 0. If the idle interval ever
/// becomes greater than or equal to the timeout interval, the request
/// is considered to have timed out. This timeout interval is measured
/// in seconds.
public var timeoutInterval: TimeInterval {
get {
return _handle.map { $0.timeoutInterval }
}
set {
_applyMutation { $0.timeoutInterval = newValue }
isTimeoutIntervalSet = true
}
}
/// The main document URL associated with this load.
/// - discussion: This URL is used for the cookie "same domain as main
/// document" policy.
public var mainDocumentURL: URL? {
get {
return _handle.map { $0.mainDocumentURL }
}
set {
_applyMutation { $0.mainDocumentURL = newValue }
}
}
/// The URLRequest.NetworkServiceType associated with this request.
/// - discussion: This will return URLRequest.NetworkServiceType.default for requests that have
/// not explicitly set a networkServiceType
public var networkServiceType: NetworkServiceType {
get {
return _handle.map { $0.networkServiceType }
}
set {
_applyMutation { $0.networkServiceType = newValue }
}
}
/// `true` if the receiver is allowed to use the built in cellular radios to
/// satisfy the request, `false` otherwise.
public var allowsCellularAccess: Bool {
get {
return _handle.map { $0.allowsCellularAccess }
}
set {
_applyMutation { $0.allowsCellularAccess = newValue }
}
}
/// The HTTP request method of the receiver.
public var httpMethod: String? {
get {
return _handle.map { $0.httpMethod }
}
set {
_applyMutation {
if let value = newValue {
$0.httpMethod = value
} else {
$0.httpMethod = "GET"
}
}
}
}
/// A dictionary containing all the HTTP header fields of the
/// receiver.
public var allHTTPHeaderFields: [String : String]? {
get {
return _handle.map { $0.allHTTPHeaderFields }
}
set {
_applyMutation { $0.allHTTPHeaderFields = newValue }
}
}
/// The value which corresponds to the given header
/// field. Note that, in keeping with the HTTP RFC, HTTP header field
/// names are case-insensitive.
/// - parameter field: the header field name to use for the lookup (case-insensitive).
public func value(forHTTPHeaderField field: String) -> String? {
return _handle.map { $0.value(forHTTPHeaderField: field) }
}
/// If a value was previously set for the given header
/// field, that value is replaced with the given value. Note that, in
/// keeping with the HTTP RFC, HTTP header field names are
/// case-insensitive.
public mutating func setValue(_ value: String?, forHTTPHeaderField field: String) {
_applyMutation {
$0.setValue(value, forHTTPHeaderField: field)
}
}
/// This method provides a way to add values to header
/// fields incrementally. If a value was previously set for the given
/// header field, the given value is appended to the previously-existing
/// value. The appropriate field delimiter, a comma in the case of HTTP,
/// is added by the implementation, and should not be added to the given
/// value by the caller. Note that, in keeping with the HTTP RFC, HTTP
/// header field names are case-insensitive.
public mutating func addValue(_ value: String, forHTTPHeaderField field: String) {
_applyMutation {
$0.addValue(value, forHTTPHeaderField: field)
}
}
/// This data is sent as the message body of the request, as
/// in done in an HTTP POST request.
public var httpBody: Data? {
get {
return _handle.map { $0.httpBody }
}
set {
_applyMutation { $0.httpBody = newValue }
}
}
/// The stream is returned for examination only; it is
/// not safe for the caller to manipulate the stream in any way. Also
/// note that the HTTPBodyStream and HTTPBody are mutually exclusive - only
/// one can be set on a given request. Also note that the body stream is
/// preserved across copies, but is LOST when the request is coded via the
/// NSCoding protocol
public var httpBodyStream: InputStream? {
get {
return _handle.map { $0.httpBodyStream }
}
set {
_applyMutation { $0.httpBodyStream = newValue }
}
}
/// `true` if cookies will be sent with and set for this request; otherwise `false`.
public var httpShouldHandleCookies: Bool {
get {
return _handle.map { $0.httpShouldHandleCookies }
}
set {
_applyMutation { $0.httpShouldHandleCookies = newValue }
}
}
/// `true` if the receiver should transmit before the previous response
/// is received. `false` if the receiver should wait for the previous response
/// before transmitting.
public var httpShouldUsePipelining: Bool {
get {
return _handle.map { $0.httpShouldUsePipelining }
}
set {
_applyMutation { $0.httpShouldUsePipelining = newValue }
}
}
public func hash(into hasher: inout Hasher) {
hasher.combine(_handle.map { $0 })
}
public static func ==(lhs: URLRequest, rhs: URLRequest) -> Bool {
return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference())
}
}
extension URLRequest : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
if let u = url {
return u.description
} else {
return "url: nil"
}
}
public var debugDescription: String {
return self.description
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "url", value: url as Any))
c.append((label: "cachePolicy", value: cachePolicy.rawValue))
c.append((label: "timeoutInterval", value: timeoutInterval))
c.append((label: "mainDocumentURL", value: mainDocumentURL as Any))
c.append((label: "networkServiceType", value: networkServiceType))
c.append((label: "allowsCellularAccess", value: allowsCellularAccess))
c.append((label: "httpMethod", value: httpMethod as Any))
c.append((label: "allHTTPHeaderFields", value: allHTTPHeaderFields as Any))
c.append((label: "httpBody", value: httpBody as Any))
c.append((label: "httpBodyStream", value: httpBodyStream as Any))
c.append((label: "httpShouldHandleCookies", value: httpShouldHandleCookies))
c.append((label: "httpShouldUsePipelining", value: httpShouldUsePipelining))
return Mirror(self, children: c, displayStyle: .struct)
}
}
extension URLRequest : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSURLRequest.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURLRequest {
return _handle._copiedReference()
}
public static func _forceBridgeFromObjectiveC(_ input: NSURLRequest, result: inout URLRequest?) {
result = URLRequest(_bridged: input)
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSURLRequest, result: inout URLRequest?) -> Bool {
result = URLRequest(_bridged: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURLRequest?) -> URLRequest {
var result: URLRequest? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
| apache-2.0 |
creatubbles/ctb-api-swift | CreatubblesAPIClientIntegrationTests/Spec/Group/NewGroupResponseHandlerSpec.swift | 1 | 3762 | //
// NewGroupResponseHandlerSpec.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Quick
import Nimble
@testable import CreatubblesAPIClient
class NewGroupResponseHandlerSpec: QuickSpec {
override func spec() {
describe("New Group response handler") {
it("Should create new group when only name is passed") {
guard let name = TestConfiguration.testNewGroupDataName
else { return }
let data = NewGroupData(name: name)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(NewGroupRequest(data: data), withResponseHandler: NewGroupResponseHandler {
(group, error) -> (Void) in
expect(group).notTo(beNil())
expect(error).to(beNil())
sender.logout()
done()
})
}
}
}
//TODO: uncomment/remove when status is determined on api - for now creating with creation's id as avatar does not work
xit("Should create new group when name and avatar_id are passed") {
guard let name = TestConfiguration.testNewGroupDataName,
let creationIdentifier = TestConfiguration.testCreationIdentifier
else { return }
let data = NewGroupData(name: "test\(name)", avatarCreationIdentifier: creationIdentifier)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(NewGroupRequest(data: data), withResponseHandler: NewGroupResponseHandler {
(group, error) -> (Void) in
expect(group).notTo(beNil())
expect(error).to(beNil())
sender.logout()
done()
})
}
}
}
}
}
}
| mit |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Models/User/UnmanagedUser.swift | 1 | 1273 | //
// UnmanagedUser.swift
// Rocket.Chat
//
// Created by Samar Sunkaria on 8/21/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
import DifferenceKit
struct UnmanagedUser: UnmanagedObject, Equatable {
typealias Object = User
var identifier: String
var username: String
var name: String?
var privateStatus: String
var status: UserStatus
var utcOffset: Double
var avatarURL: URL?
var displayName: String
var federatedServerName: String
var managedObject: User? {
return User.find(withIdentifier: identifier)?.validated()
}
}
extension UnmanagedUser {
init?(_ user: User) {
guard let userUsername = user.username else {
return nil
}
identifier = user.identifier ?? ""
username = userUsername
name = user.name
privateStatus = user.privateStatus
status = user.status
utcOffset = user.utcOffset
avatarURL = user.avatarURL()
displayName = user.displayName()
federatedServerName = user.federatedServerName ?? ""
}
}
extension UnmanagedUser: Differentiable {
typealias DifferenceIdentifier = String
var differenceIdentifier: String {
return username
}
}
| mit |
ReedD/RolodexNavigationController | RolodexNavigationController/ChildViewController.swift | 1 | 1986 | //
// ChildViewController.swift
// RolodexNavigationController
//
// Created by Reed Dadoune on 12/7/14.
// Copyright (c) 2014 Dadoune. All rights reserved.
//
import UIKit
class ChildViewController: UIViewController {
@IBOutlet weak var previousController: UIButton!
@IBOutlet weak var nextController: UIButton!
enum ControllerNavigation: Int {
case Previous, Next
}
var rolodexController: RolodexNavigationController? {
get {
if let controller = self.navigationController?.parentViewController as? RolodexNavigationController {
return controller
}
return nil
}
}
@IBAction func showRolodexTouched(sender: AnyObject) {
self.rolodexController?.showRolodex = true;
}
@IBAction func goToController(sender: UIButton) {
if let rolodexController = self.rolodexController {
let button = ControllerNavigation(rawValue: sender.tag)
var index = 0
if let button = ControllerNavigation(rawValue: sender.tag) {
switch button {
case .Next:
index = rolodexController.selectedIndex! + 1
case .Previous:
index = rolodexController.selectedIndex! - 1
}
}
let viewController = rolodexController.viewControllers[index]
rolodexController.goToViewController(viewController, animated: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
var randomRed = CGFloat(drand48())
var randomGreen = CGFloat(drand48())
var randomBlue = CGFloat(drand48())
self.view.backgroundColor = UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.previousController?.enabled = true
self.previousController?.enabled = true
if self.rolodexController?.viewControllers.first == self.navigationController {
self.previousController?.enabled = false
} else if self.rolodexController?.viewControllers.last == self.navigationController {
self.nextController?.enabled = false
}
}
}
| mit |
schibsted/layout | Layout/LayoutNode+Layout.swift | 1 | 3550 | // Copyright © 2017 Schibsted. All rights reserved.
import Foundation
extension LayoutNode {
/// Create a new LayoutNode instance from a Layout template
convenience init(
layout: Layout,
outlet: String? = nil,
state: Any = (),
constants: [String: Any]...
) throws {
try self.init(
layout: layout,
outlet: outlet,
state: state,
constants: merge(constants),
isRoot: true
)
}
private convenience init(
layout: Layout,
outlet: String? = nil,
state: Any = (),
constants: [String: Any] = [:],
isRoot: Bool
) throws {
do {
if let path = layout.templatePath {
throw LayoutError("Cannot initialize \(layout.className) node until content for \(path) has been loaded")
}
let _class: AnyClass = try layout.getClass()
var expressions = layout.expressions
if let body = layout.body {
guard case let bodyExpression?? = _class.bodyExpression else {
throw LayoutError("\(layout.className) does not support inline (X)HTML content")
}
expressions[bodyExpression] = body
}
if let outlet = outlet {
expressions["outlet"] = outlet
}
try self.init(
class: _class,
id: layout.id,
state: state,
constants: constants,
expressions: expressions,
children: layout.children.map {
try LayoutNode(layout: $0, isRoot: false)
}
)
_parameters = layout.parameters
_macros = layout.macros
rootURL = layout.rootURL
guard let xmlPath = layout.xmlPath else {
return
}
var deferredError: Error?
LayoutLoader().loadLayout(
withContentsOfURL: urlFromString(xmlPath, relativeTo: rootURL),
relativeTo: layout.relativePath
) { [weak self] layout, error in
if let layout = layout {
do {
try self?.update(with: layout)
} catch {
deferredError = error
}
} else if let error = error {
deferredError = error
}
}
// TODO: what about errors thrown by deferred load?
if let error = deferredError {
throw error
}
} catch {
throw LayoutError(error, in: layout.className, in: isRoot ? layout.rootURL : nil)
}
}
}
extension Layout {
// Experimental - extracts a layout template from an existing node
// TODO: this isn't a lossless conversion - find a better approach
init(_ node: LayoutNode) {
self.init(
className: nameOfClass(node._class),
id: node.id,
expressions: node._originalExpressions,
parameters: node._parameters,
macros: node._macros,
children: node.children.map(Layout.init(_:)),
body: nil,
xmlPath: nil, // TODO: what if the layout is currently loading this? Race condition!
templatePath: nil,
childrenTagIndex: nil,
relativePath: nil,
rootURL: node.rootURL
)
}
}
| mit |
josve05a/wikipedia-ios | Wikipedia/Code/WMFChangePasswordViewController.swift | 3 | 6665 | import WMF
import UIKit
class WMFChangePasswordViewController: WMFScrollViewController, Themeable {
@IBOutlet fileprivate var titleLabel: UILabel!
@IBOutlet fileprivate var subTitleLabel: UILabel!
@IBOutlet fileprivate var passwordField: ThemeableTextField!
@IBOutlet fileprivate var retypeField: ThemeableTextField!
@IBOutlet fileprivate var passwordTitleLabel: UILabel!
@IBOutlet fileprivate var retypeTitleLabel: UILabel!
@IBOutlet fileprivate var saveButton: WMFAuthButton!
fileprivate var theme: Theme = Theme.standard
public var funnel: WMFLoginFunnel?
public var userName:String?
@IBAction fileprivate func saveButtonTapped(withSender sender: UIButton) {
save()
}
@IBAction func textFieldDidChange(_ sender: UITextField) {
guard
let password = passwordField.text,
let retype = retypeField.text
else{
enableProgressiveButton(false)
return
}
enableProgressiveButton((!password.isEmpty && !retype.isEmpty))
}
fileprivate func passwordFieldsMatch() -> Bool {
return passwordField.text == retypeField.text
}
func enableProgressiveButton(_ highlight: Bool) {
saveButton.isEnabled = highlight
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
enableProgressiveButton(false)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
passwordField.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
enableProgressiveButton(false)
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if (textField == passwordField) {
retypeField.becomeFirstResponder()
} else if (textField == retypeField) {
save()
}
return true
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"close"), style: .plain, target:self, action:#selector(closeButtonPushed(_:)))
navigationItem.leftBarButtonItem?.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
titleLabel.text = WMFLocalizedString("new-password-title", value:"Set your password", comment:"Title for password change interface")
subTitleLabel.text = WMFLocalizedString("new-password-instructions", value:"You logged in with a temporary password. To finish logging in set a new password here.", comment:"Instructions for password change interface")
passwordField.placeholder = WMFLocalizedString("field-new-password-placeholder", value:"enter new password", comment:"Placeholder text shown inside new password field until user taps on it")
retypeField.placeholder = WMFLocalizedString("field-new-password-confirm-placeholder", value:"re-enter new password", comment:"Placeholder text shown inside confirm new password field until user taps on it")
passwordTitleLabel.text = WMFLocalizedString("field-new-password-title", value:"New password", comment:"Title for new password field")
retypeTitleLabel.text = WMFLocalizedString("field-new-password-confirm-title", value:"Confirm new password", comment:"Title for confirm new password field")
view.wmf_configureSubviewsForDynamicType()
apply(theme: theme)
}
@objc func closeButtonPushed(_ : UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
fileprivate func save() {
guard passwordFieldsMatch() else {
WMFAlertManager.sharedInstance.showErrorAlertWithMessage(WMFLocalizedString("account-creation-passwords-mismatched", value:"Password fields do not match.", comment:"Alert shown if the user doesn't enter the same password in both password boxes"), sticky: true, dismissPreviousAlerts: true, tapCallBack: nil)
passwordField.text = nil
retypeField.text = nil
passwordField.becomeFirstResponder()
return
}
wmf_hideKeyboard()
enableProgressiveButton(false)
WMFAlertManager.sharedInstance.dismissAlert()
guard let userName = userName,
let password = passwordField.text,
let retypePassword = retypeField.text else {
assertionFailure("One or more of the required parameters are nil")
return
}
WMFAuthenticationManager.sharedInstance.login(username: userName, password: password, retypePassword: retypePassword, oathToken: nil, captchaID: nil, captchaWord: nil) { (loginResult) in
switch loginResult {
case .success(_):
let loggedInMessage = String.localizedStringWithFormat(WMFLocalizedString("main-menu-account-title-logged-in", value:"Logged in as %1$@", comment:"Header text used when account is logged in. %1$@ will be replaced with current username."), userName)
WMFAlertManager.sharedInstance.showSuccessAlert(loggedInMessage, sticky: false, dismissPreviousAlerts: true, tapCallBack: nil)
self.dismiss(animated: true, completion: nil)
self.funnel?.logSuccess()
case .failure(let error):
self.enableProgressiveButton(true)
WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil)
self.funnel?.logError(error.localizedDescription)
if let error = error as? URLError {
if error.code != .notConnectedToInternet {
self.passwordField.text = nil
self.retypeField.text = nil
}
}
default:
break
}
}
}
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
view.tintColor = theme.colors.link
let labels = [titleLabel, subTitleLabel, passwordTitleLabel, retypeTitleLabel]
for label in labels {
label?.textColor = theme.colors.secondaryText
}
let fields = [passwordField, retypeField]
for field in fields {
field?.apply(theme: theme)
}
saveButton.apply(theme: theme)
}
}
| mit |
kevinhankens/runalysis | Runalysis/RouteSummary.swift | 1 | 13070 | //
// RouteSummaryView.swift
// Runalysis
//
// Created by Kevin Hankens on 9/3/14.
// Copyright (c) 2014 Kevin Hankens. All rights reserved.
//
import Foundation
import UIKit
/*!
* Provides a summary of a list of Route objects.
*/
class RouteSummary: NSObject {
// Tracks the route store.
var routeStore: RouteStore?
// Tracks the current route ID.
var routeId: NSNumber = 0
// Tracks a list of route points.
var points: [AnyObject]?
// The lowest velocity, currently 0.
var velocity_low: CLLocationSpeed = Double(0)
var mov_avg_low: CLLocationSpeed = Double(0)
// The highest velocity reached.
var velocity_high: CLLocationSpeed = Double(0)
var mov_avg_high: CLLocationSpeed = Double(0)
// The quantile for each bin.
var velocity_step: CLLocationSpeed = Double(0)
var mov_avg_step: CLLocationSpeed = Double(0)
// The mean velocity over the course.
var velocity_mean: CLLocationSpeed = Double(0)
// The total distance traveled.
var distance_total: CLLocationDistance = Double(0)
// Tracks a distribution of velocities relative to the mean.
var distribution = [0, 0, 0, 0, 0, 0, 0, 0, 0]
var mov_avg_dist = [0, 0, 0, 0, 0, 0, 0, 0, 0]
var animation_length: Int = 0
// Tracks the duration of the run.
var duration: Double = Double(0)
// Tracks the times for each mile run.
var mileTimes: [Double] = []
/*!
* Factory method to create a summary.
*
* @param NSNumber routeId
* @param RouteStore routeStore
*
* @return RouteSummary
*/
class func createRouteSummary(routeId: NSNumber, routeStore: RouteStore)->RouteSummary {
let rsv = RouteSummary()
rsv.routeStore = routeStore
rsv.updateRoute(routeId)
return rsv
}
/*!
* Upstes the summary to a new set of points.
*
* @param NSNumber id
*/
func updateRoute(id: NSNumber) {
if id == self.routeId {
// @todo != creates an error "ambiguous use of !="
}
else {
self.routeId = id
}
// @todo can we skip this if the screen is locked?
self.points = self.routeStore!.getPointsForId(self.routeId)
self.calculateSummary()
}
/*!
* Gets a label for the total mileage with the pace.
*
* @return String
*/
func getTotalAndPace()->String {
return "\(self.totalDistance())\(RunalysisUnits.getUnitLabel()) @\(self.avgVelocityInMinutesPerUnit())"
}
/*!
* Gets the total in miles.
*
* @return String
*/
func totalDistance()->String {
let total = RunalysisUnits.convertMetersToUnits(self.distance_total)
let rounded = round(total * 100)/100
let miles = Int(rounded)
let fraction = Int((rounded - Double(miles)) * 100)
var fraction_string = "\(fraction)"
if fraction < 10 {
fraction_string = "0\(fraction)"
}
return "\(miles).\(fraction_string)"
}
/*!
* Gets a label for the average pace in minutes per mile.
*
* @return String
*/
func avgVelocityInMinutesPerUnit()->String {
let unitsPerMinute = RunalysisUnits.getVelocityPerUnit(self.velocity_mean)/Double(60)
if unitsPerMinute > 0 {
let minutesPerUnit = Double(1)/unitsPerMinute
let minutes = Int(minutesPerUnit)
let seconds = Int(round((minutesPerUnit - Double(minutes)) * 60))
var seconds_string = "\(String(seconds))"
if seconds < Int(10) {
seconds_string = "0\(String(seconds))"
}
return "\(String(minutes)):\(seconds_string)"
}
return "0:00"
}
/*!
* Calculates the averages and totals for the set of points.
*/
func calculateSummary() {
self.velocity_low = Double(0)
self.velocity_high = Double(0)
self.velocity_mean = Double(0)
self.distance_total = Double(0)
self.mov_avg_low = Double(0)
self.mov_avg_high = Double(0)
self.calculateVelocity()
self.calculateDistribution()
//println("Distribution: \(self.distribution)");
//println("Low: \(self.velocity_low)");
//println("High: \(self.velocity_high)");
//println("Mean: \(self.velocity_mean)");
//println("Dist: \(self.distance_total)");
}
/*!
* Calculates the average velocity and the total distance.
*/
func calculateVelocity() {
var count = 0
var total = Double(0)
var started = false
var duration = Double(0)
self.mileTimes.removeAll(keepCapacity: false)
var unitCount = 0
var unitTime = Double(0.0)
var unitTimeTmp = Double(0.0)
var distanceTotal = Double(0.0)
var movingAverage: [Double] = [0, 0, 0, 0, 0]
var movingAverageTotal = Double(0.0)
if self.points?.count > 0 {
var velocityRange = [Double](count: self.points!.count, repeatedValue: 0.0)
// Find outliers.
var i = 0
for p in self.points! {
if let point = p as? Route {
// Track the raw double value to speed up drawing.
point.latitude_raw = point.latitude.doubleValue
point.longitude_raw = point.longitude.doubleValue
point.altitude_raw = point.altitude.doubleValue
// Track the range of velocity points.
point.velocity_raw = point.velocity.doubleValue
velocityRange[i] = point.velocity_raw
}
i++
}
// Determine inner fences.
velocityRange.sort { $0 < $1 }
let q25 = locateQuantile(0.25, values: velocityRange)
let q75 = locateQuantile(0.75, values: velocityRange)
let qr = 1.5 * (q75 - q25)
let bl = q25 - qr
let bu = q75 + qr
var vlow = 0.0
var vhigh = 0.0
var malow = 0.0
var mahigh = 0.0
var movingAveragePos = 0
for p in self.points! {
if let point = p as? Route {
if !started {
// skip the first one as 0 velocity skews the averages.
started = true
continue
}
let testv: AnyObject? = point.valueForKey("velocity")
if let v = testv as? NSNumber {
// Determine the moving average by compiling a list
// of trailing values.
movingAverageTotal -= movingAverage[movingAveragePos]
movingAverageTotal += point.velocity_raw
movingAverage[movingAveragePos] = point.velocity_raw
movingAveragePos++
if movingAveragePos > 4 {
movingAveragePos = 0
}
// Set the new velocity if the moving average array
// has enough values to be significant.
if count > 4 {
point.velocityMovingAvg = movingAverageTotal / Double(movingAverage.count)
}
else {
point.velocityMovingAvg = point.velocity_raw
}
if point.velocity_raw > Double(0.0) {
// Check for outliers.
if point.velocity_raw > bu {
point.velocity = NSNumber(double: bu)
point.velocity_raw = bu
}
if point.velocity_raw < vlow || vlow == Double(0) {
// @todo low is always 0.
vlow = point.velocity_raw
}
else if point.velocity_raw > vhigh {
vhigh = point.velocity_raw
}
if point.velocityMovingAvg < malow || malow == Double(0) {
malow = point.velocityMovingAvg
}
else if point.velocityMovingAvg > mahigh {
mahigh = point.velocityMovingAvg
}
distanceTotal += Double(point.distance)
total += Double(point.velocity)
duration += Double(point.interval)
count++
}
}
// Track the miles.
if Int(RunalysisUnits.convertMetersToUnits(distanceTotal)) > unitCount {
unitCount++
unitTimeTmp = duration - unitTime
unitTime = duration
self.mileTimes.append(unitTimeTmp)
}
}
}
self.distance_total = distanceTotal
self.velocity_low = vlow
self.velocity_high = vhigh
self.mov_avg_low = malow
self.mov_avg_high = mahigh
}
if count > 0 {
self.velocity_mean = total/Double(count)
self.duration = duration
}
}
/*!
* Locates the quantile given an array of sorted values.
*
* @param quantile
* @param values
*
* @return Double
*/
func locateQuantile(quantile: Double, values: [Double])->Double {
let length = values.count
let index = quantile * Double(length-1)
let boundary = Int(index)
let delta = index - Double(boundary)
if length == 0 {
return 0.0
} else if boundary == length-1 {
return values[boundary]
} else {
return (1-delta)*values[boundary] + delta*values[boundary+1]
}
}
/*!
* Calculates the distribution of velocities.
*/
func calculateDistribution() {
var rel = 0
// For some reason trying to adjust self.distribution is very expensive. So do it in a local var and update once at the end.
var tmp = [0,0,0,0,0,0,0,0,0]
var tmp_mov = [0,0,0,0,0,0,0,0,0]
let velocityDiff = self.velocity_high - self.velocity_low
self.velocity_step = velocityDiff/Double(tmp.count)
let velocityDiffMov = self.mov_avg_high - self.mov_avg_low
self.mov_avg_step = velocityDiffMov/Double(tmp_mov.count)
if self.points?.count > 0 {
for p: AnyObject in self.points! {
if let point = p as? Route {
// This is a little overkill, but the simulator occasionally
// fails leaving an invalid point in the db due to a null value
// for the velocity column. Strange because it's got a default
// value of 0. This is the only way I've found to prevent crashing.
let testv: AnyObject? = point.valueForKey("velocity")
if let v = testv as? NSNumber {
rel = self.getRelativeVelocity(point.velocity_raw, low: self.velocity_low, step: self.velocity_step)
point.relativeVelocity = rel
tmp[rel]++
rel = self.getRelativeVelocity(point.velocityMovingAvg, low: self.velocity_low, step: self.velocity_step)
point.relVelMovingAvg = rel
tmp_mov[rel]++
}
}
}
}
var i = 0
for i = 0; i < tmp.count; i++ {
self.distribution[i] = tmp[i]
self.mov_avg_dist[i] = tmp_mov[i]
}
}
/*!
* Gets the relative velocity of a point compared to the high, low and average.
*
* @return NSNumber
*/
func getRelativeVelocity(velocity: Double, low: CLLocationSpeed, step: CLLocationSpeed)->Int {
var rel = 0
for var i = 0; i < self.distribution.count; i++ {
if velocity < low + (step * Double((i + 1))) {
rel = i
break
}
}
return rel
}
}
| mit |
JohnPJenkins/swift-t | stc/tests/691-file-copy.swift | 4 | 589 | import files;
import assert;
main () {
file a<"691-tmp.txt"> = write("contents.");
// Check we can copy to mapped and unmapped files
file b = a;
assertEqual(read(b), "contents.", "b");
file c<"691-tmp2.txt">;
// unmapped to mapped
c = copy_wrapper(a);
// unmapped to unmapped
file d = copy_wrapper(b);
assertEqual(read(d), "contents.", "d");
// mapped to mapped
file e<"691-tmp3.txt"> = c;
assertEqual(read(e), "contents.", "e");
}
(file o) copy_wrapper (file i) {
// Don't know mapping status of these files
o = i;
}
| apache-2.0 |
Vaseltior/SFCore | SFCoreTests/ArrayTests.swift | 1 | 1035 | //
// ArrayTests.swift
// SFCore
//
// Created by Samuel Grau on 10/04/2016.
// Copyright © 2016 Samuel Grau. All rights reserved.
//
import XCTest
@testable import SFCore
class ArrayTests: XCTestCase {
func testArrayFunctions() {
let a = [1, 5, 8, 9, 11]
XCTAssertEqual(a.sfFirstObject(), 1)
XCTAssertEqual(a.sfLastObject(), 11)
XCTAssertTrue(a.sfIsIndexInBounds(0))
XCTAssertTrue(a.sfIsIndexInBounds(3))
XCTAssertTrue(a.sfIsIndexInBounds(4))
XCTAssertFalse(a.sfIsIndexInBounds(-1))
XCTAssertFalse(a.sfIsIndexInBounds(5))
XCTAssertFalse(a.sfIsIndexOutOfBounds(0))
XCTAssertFalse(a.sfIsIndexOutOfBounds(3))
XCTAssertFalse(a.sfIsIndexOutOfBounds(4))
XCTAssertTrue(a.sfIsIndexOutOfBounds(-1))
XCTAssertTrue(a.sfIsIndexOutOfBounds(5))
XCTAssertTrue(Array<Int>.isSortedAscendingly(a))
let b = [1,5,1,9,11]
XCTAssertFalse(Array<Int>.isSortedAscendingly(b))
let c: Array<Int> = []
XCTAssertNil(c.sfFirstObject())
XCTAssertNil(c.sfLastObject())
}
}
| mit |
onmyway133/LighterAppDelegate | Pod/Classes/Dispatcher/Dispatcher+RemoteNotification.swift | 1 | 2373 | //
// Dispatcher+RemoteNotification.swift
// Pods
//
// Created by Khoa Pham on 1/15/16.
// Copyright © 2016 Fantageek. All rights reserved.
//
import Foundation
// Handling Remote Notifications
public extension Dispatcher {
public func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
services.forEach { service in
service.application?(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
}
}
public func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
services.forEach { service in
service.application?(application, didFailToRegisterForRemoteNotificationsWithError: error)
}
}
public func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
services.forEach { service in
service.application?(application, didReceiveRemoteNotification: userInfo)
}
}
public func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
services.forEach { service in
service.application?(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)
}
}
public func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], completionHandler: () -> Void) {
services.forEach { service in
service.application?(application, handleActionWithIdentifier: identifier, forRemoteNotification: userInfo, completionHandler: completionHandler)
}
}
@available(iOS 9.0, *)
public func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], withResponseInfo responseInfo: [NSObject : AnyObject], completionHandler: () -> Void) {
services.forEach { service in
service.application?(application, handleActionWithIdentifier: identifier, forRemoteNotification: userInfo, withResponseInfo: responseInfo, completionHandler: completionHandler)
}
}
} | mit |
bixubot/AcquainTest | ChatRoom/ChatRoom/AvatarTableViewCell.swift | 1 | 2438 | //
// AvatarTableViewCell.swift
// ChatRoom
//
// Created by Mutian on 4/21/17.
// Copyright © 2017 Binwei Xu. All rights reserved.
//
import UIKit
import Firebase
class AvatarTableViewCell: UITableViewCell {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var nicknameLabel: UILabel!
@IBOutlet weak var chatIDLabel: UILabel!
// fetch User object from NewMessageController and pass to chatlogcontroller
var user: User?
func fetchUserAndSetupNavBarTitle() {
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
// for some reason uid = nil
return
}
FIRDatabase.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: Any] {
self.user?.setValuesForKeys(dictionary)
}
}, withCancel: nil)
}
/**
Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file.
@param None
@return None
*/
override func awakeFromNib() {
super.awakeFromNib()
self.accessoryType = .disclosureIndicator
self.avatarImageView.layer.masksToBounds = true
self.avatarImageView.layer.cornerRadius = self.avatarImageView.bounds.size.width/2/180 * 30
self.avatarImageView.layer.borderWidth = 0.5
self.avatarImageView.layer.borderColor = UIColor.lightGray.cgColor
self.avatarImageView.translatesAutoresizingMaskIntoConstraints = false
self.nicknameLabel.translatesAutoresizingMaskIntoConstraints = false
self.chatIDLabel.translatesAutoresizingMaskIntoConstraints = false
// fetchUserAndSetupNavBarTitle()
//
// if let profileImageUrl = self.user?.profileImageUrl {
// self.avatarImageView.loadImageUsingCacheWithUrlString(urlString: profileImageUrl)
// }
// self.nicknameLabel.text = user?.name
// self.chatIDLabel.text = user?.email
}
/**
Configure the view for the selected state
@param None
@return None
*/
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
MichaelBuckley/MAIKit | Examples/Circles/Circles/Mac/AppDelegate.swift | 2 | 498 | //
// AppDelegate.swift
// Circles
//
// Created by Buckley on 6/14/15.
// Copyright © 2015 Buckleyisms. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
| mit |
TouchInstinct/LeadKit | Sources/Extensions/DataLoading/Rx+RxDataSourceProtocol.swift | 1 | 1710 | //
// Copyright (c) 2018 Touch Instinct
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import RxSwift
import RxCocoa
extension Observable: RxDataSource {
public typealias ResultType = Element
public func resultSingle() -> Single<ResultType> {
asSingle()
}
}
// waiting for Swift 4.2 release...
// https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md
// extension PrimitiveSequence: RxDataSource where Trait == SingleTrait {
extension Single: RxDataSource {
public typealias ResultType = Element
public func resultSingle() -> Single<ResultType> {
asObservable().asSingle()
}
}
| apache-2.0 |
radex/swift-compiler-crashes | crashes-fuzzing/00530-swift-metatypetype-get.swift | 11 | 237 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class C{{
}
static
func c<g{
{
}
class d{{}
struct d<c where g.i=c.i | mit |
jarrroo/MarkupKitLint | Tools/Pods/Nimble/Sources/Nimble/Matchers/BeginWith.swift | 33 | 2634 | import Foundation
/// A Nimble matcher that succeeds when the actual sequence's first element
/// is equal to the expected value.
public func beginWith<S: Sequence, T: Equatable>(_ startingElement: T) -> Predicate<S>
where S.Iterator.Element == T {
return Predicate.simple("begin with <\(startingElement)>") { actualExpression in
if let actualValue = try actualExpression.evaluate() {
var actualGenerator = actualValue.makeIterator()
return PredicateStatus(bool: actualGenerator.next() == startingElement)
}
return .fail
}
}
/// A Nimble matcher that succeeds when the actual collection's first element
/// is equal to the expected object.
public func beginWith(_ startingElement: Any) -> Predicate<NMBOrderedCollection> {
return Predicate.simple("begin with <\(startingElement)>") { actualExpression in
guard let collection = try actualExpression.evaluate() else { return .fail }
guard collection.count > 0 else { return .doesNotMatch }
#if os(Linux)
guard let collectionValue = collection.object(at: 0) as? NSObject else {
return .fail
}
#else
let collectionValue = collection.object(at: 0) as AnyObject
#endif
return PredicateStatus(bool: collectionValue.isEqual(startingElement))
}
}
/// A Nimble matcher that succeeds when the actual string contains expected substring
/// where the expected substring's location is zero.
public func beginWith(_ startingSubstring: String) -> Predicate<String> {
return Predicate.simple("begin with <\(startingSubstring)>") { actualExpression in
if let actual = try actualExpression.evaluate() {
let range = actual.range(of: startingSubstring)
return PredicateStatus(bool: range != nil && range!.lowerBound == actual.startIndex)
}
return .fail
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beginWithMatcher(_ expected: Any) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let actual = try! actualExpression.evaluate()
if (actual as? String) != nil {
let expr = actualExpression.cast { $0 as? String }
return try! beginWith(expected as! String).matches(expr, failureMessage: failureMessage)
} else {
let expr = actualExpression.cast { $0 as? NMBOrderedCollection }
return try! beginWith(expected).matches(expr, failureMessage: failureMessage)
}
}
}
}
#endif
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.